共用方式為


HOW TO:寫入文字檔 (C# 程式設計手冊)

在下列這些範例中,會示範幾個將文字寫入檔案的方法。 前兩個範例會在 System.IO.File 類別 (Class) 上使用靜態 (Static) 方法,將完整字串陣列或完整字串寫入文字檔。 在第三個範例中,會示範如何在需要處理每一行時將文字加入至檔案,然後才寫入檔案。 第一個範例到第三個範例都會覆寫檔案中的全部現有內容。 在第四個範例中,會示範如何將文字附加至現有的檔案。

範例

    class WriteTextFile
    {
        static void Main()
        {

            // These examples assume a "C:\Users\Public\TestFolder" folder on your machine.
            // You can modify the path if necessary.

            // Example #1: Write an array of strings to a file.
            // Create a string array that consists of three lines.
            string[] lines = {"First line", "Second line", "Third line"};
            System.IO.File.WriteAllLines(@"C:\Users\Public\TestFolder\WriteLines.txt", lines);


            // Example #2: Write one string to a text file.
            string text = "A class is the most powerful data type in C#. Like structures, " +
                           "a class defines the data and behavior of the data type. ";
            System.IO.File.WriteAllText(@"C:\Users\Public\TestFolder\WriteText.txt", text);

            // Example #3: Write only some strings in an array to a file.
            using (System.IO.StreamWriter file = new System.IO.StreamWriter(@"C:\Users\Public\TestFolder\WriteLines2.txt"))
            {
                foreach (string line in lines)
                {
                    // If the line doesn't contain the word 'Second', write the line to the file.
                    if (!line.Contains("Second"))
                    {
                        file.WriteLine(line);
                    }
                }
            }

            // Example #4: Append new text to an existing file
            using (System.IO.StreamWriter file = new System.IO.StreamWriter(@"C:\Users\Public\TestFolder\WriteLines2.txt", true))
            {
                file.WriteLine("Fourth line");
            }  
        }
    }
    /* Output (to WriteLines.txt):
        First line
        Second line
        Third line

     Output (to WriteText.txt):
        A class is the most powerful data type in C#. Like structures, a class defines the data and behavior of the data type.

     Output to WriteLines2.txt after Example #3:
        First line
        Third line

     Output to WriteLines2.txt after Example #4:
        First line
        Third line
        Fourth line
     */

編譯程式碼

將程式碼複製至主控台應用程式 (Console Application)。

以您電腦上的實際資料夾名稱來取代 "c:\testdir",或以那個名稱來建立資料夾。

穩固程式設計

下列情形可能會造成例外狀況 (Exception):

  • 該檔案存在而且是唯讀的。

  • 路徑名稱可能太長。

  • 磁碟可能已滿。

請參閱

概念

C# 程式設計手冊

其他資源

檔案系統和登錄 (C# 程式設計手冊)