利用 Visual C# 讀取及寫入文字檔

本文可協助您利用 Visual C# 讀取及寫入文字檔。

原始產品版本: Visual Studio
原始 KB 編號: 816149

摘要

本文的「讀取文字檔」一節說明如何使用 StreamReader 類別來讀取文字檔。 寫入文字檔 (範例 1)寫入文字檔 (範例 2) 章節說明如何使用 StreamWriter 類別把文字寫入檔案。

讀取文字檔

下列程式碼會使用 StreamReader 類別來開啟、讀取及關閉文字檔。 您可以將文字檔的路徑傳遞至 StreamReader 建構函式,以便自動開啟檔案。 ReadLine 方法會讀取每一行文字,並在讀取時將檔案指標遞增至下一行。 當 ReadLine 方法到達檔案末端時,會傳回 null 參照。 如需詳細資訊,請參閱 StreamReader 類別

  1. 在記事本中建立範例文字檔。 請遵循下列步驟:

    1. 在記事本中貼上 hello world 文字。
    2. 將檔案儲存為 Sample.txt
  2. 啟動 Microsoft Visual Studio。

  3. [檔案] 功能表中,指向 [新增],然後選取 [專案]

  4. 選取 [Project 類型] 底下的 [Visual C# 專案],然後選取 [範本] 底下的 [主控台應用程式]。

  5. 將下列程式碼加到 Class1.cs 檔的開頭:

    using System.IO;
    
  6. 將下列程式碼加到 Main 方法:

    String line;
    try
    {
        //Pass the file path and file name to the StreamReader constructor
        StreamReader sr = new StreamReader("C:\\Sample.txt");
        //Read the first line of text
        line = sr.ReadLine();
        //Continue to read until you reach end of file
        while (line != null)
        {
            //write the line to console window
            Console.WriteLine(line);
            //Read the next line
            line = sr.ReadLine();
        }
        //close the file
        sr.Close();
        Console.ReadLine();
    }
    catch(Exception e)
    {
        Console.WriteLine("Exception: " + e.Message);
    }
    finally
    {
        Console.WriteLine("Executing finally block.");
    }
    
  7. 在 [偵錯] 功能表上,選取 [開始] 來編譯及執行應用程式。 按下 [ENTER] 關閉 [主控台] 視窗。 主控台視窗會顯示 Sample.txt 檔的內容:

    Hello world
    

寫入文字檔 (範例 1)

下列程式碼會使用 StreamWriter 類別來開啟、寫入及關閉文字檔。 透過類似 StreamReader 類別的方式,您可以把文字檔的路徑傳遞給 StreamWriter 建構函式,以便自動開啟檔案。 WriteLine 方法會把一整行文字寫入文字檔。

  1. 啟動 Visual Studio。

  2. [檔案] 功能表中,指向 [新增],然後選取 [專案]

  3. 選取 [Project 類型] 底下的 [Visual C# 專案],然後選取 [範本] 底下的 [主控台應用程式]。

  4. 將下列程式碼加到 Class1.cs 檔的開頭:

    using System.IO;
    
  5. 將下列程式碼加到 Main 方法:

    try
    {
        //Pass the filepath and filename to the StreamWriter Constructor
        StreamWriter sw = new StreamWriter("C:\\Test.txt");
        //Write a line of text
        sw.WriteLine("Hello World!!");
        //Write a second line of text
        sw.WriteLine("From the StreamWriter class");
        //Close the file
        sw.Close();
    }
    catch(Exception e)
    {
        Console.WriteLine("Exception: " + e.Message);
    }
    finally
    {
        Console.WriteLine("Executing finally block.");
    }
    
  6. 在 [偵錯] 功能表上,選取 [開始] 來編譯及執行應用程式。 這段程式碼會在 C 磁碟上建立名為 Test.txt 的檔案。利用像記事本之類的文字編輯器開啟 Test.txt 檔。 Test.txt 包含兩行文字:

    Hello World!!
    From the StreamWriter class
    

寫入文字檔 (範例 2)

下列程式碼會使用 StreamWriter 類別來開啟、寫入及關閉文字檔。 不同於上一個範例,這個程式碼會把兩個額外的參數傳遞至建構函式。 第一個參數是檔案路徑和檔案的檔案名稱。 第二個參數是 true,指定以附加模式開啟檔案。 如果您指定 false 作為第二個參數,則每次執行程式碼時會覆寫檔案內容。 第三個參數指定 Unicode,因此 StreamWriter 會以 Unicode 格式對檔案進行編碼。 您也可以指定下列編碼方式作為第三個參數:

  • ASC11
  • Unicode
  • UTF7
  • UTF-8

Write 方法跟 WriteLine 方法相似,但 Write 方法不會自動嵌入歸位或換行 (CR/LF) 字元組合。 當您一次只撰寫一個字元時,這很有幫助。

  1. 啟動 Visual Studio。

  2. [檔案] 功能表中,按一下 [新增],然後按一下 [專案]

  3. [專案類型] 底下,按一下 [Visual C# 專案],然後按一下 [範本] 下的 [主控台應用程式]

  4. 將下列程式碼加到 Class1.cs 檔的開頭:

    using System.IO;
    using System.Text;
    
  5. 將下列程式碼加到 Main 方法:

    Int64 x;
    try
    {
        //Open the File
        StreamWriter sw = new StreamWriter("C:\\Test1.txt", true, Encoding.ASCII);
    
        //Write out the numbers 1 to 10 on the same line.
        for(x=0; x < 10; x++)
        {
        sw.Write(x);
        }
    
        //close the file
        sw.Close();
    }
    catch(Exception e)
    {
        Console.WriteLine("Exception: " + e.Message);
    }
    finally
    {
        Console.WriteLine("Executing finally block.");
    }
    
  6. 在 [偵錯] 功能表上,選取 [開始] 來編譯及執行應用程式。 這段程式碼會在 C 磁碟建立名為 Test1.txt 的檔案。請在記事本這類文字編輯器中開啟 Test1.txt 檔。 Test1.txt 包含單行文字:0123456789

有關如何讀取文字檔的完整程式碼清單

//Read a Text File
using System;
using System.IO;
namespace readwriteapp
{
    class Class1
    {
        [STAThread]
        static void Main(string[] args)
        {
            String line;
            try
            {
                //Pass the file path and file name to the StreamReader constructor
                StreamReader sr = new StreamReader("C:\\Sample.txt");
                //Read the first line of text
                line = sr.ReadLine();
                //Continue to read until you reach end of file
                while (line != null)
                {
                    //write the line to console window
                    Console.WriteLine(line);
                    //Read the next line
                    line = sr.ReadLine();
                }
                //close the file
                sr.Close();
                Console.ReadLine();
            }
            catch(Exception e)
            {
                Console.WriteLine("Exception: " + e.Message);
            }
            finally
            {
                Console.WriteLine("Executing finally block.");
            }
        }
    }
}

有關如何寫入文字檔的完整程式碼清單 (版本 1)

//Write a text file - Version-1
using System;
using System.IO;
namespace readwriteapp
{
    class Class1
    {
        [STAThread]
        static void Main(string[] args)
        {
            try
            {
                //Pass the filepath and filename to the StreamWriter Constructor
                StreamWriter sw = new StreamWriter("C:\\Test.txt");
                //Write a line of text
                sw.WriteLine("Hello World!!");
                //Write a second line of text
                sw.WriteLine("From the StreamWriter class");
                //Close the file
                sw.Close();
            }
            catch(Exception e)
            {
                Console.WriteLine("Exception: " + e.Message);
            }
            finally
            {
                Console.WriteLine("Executing finally block.");
            }
        }
    }
}

有關如何將文字檔寫入的完整程式碼清單 (版本 2)

//Write a text file - Version 2
using System;
using System.IO;
using System.Text;
namespace readwriteapp
{
    class Class1
    {
        [STAThread]
        static void Main(string[] args)
        {
            Int64 x;
            try
            {
                //Open the File
                StreamWriter sw = new StreamWriter("C:\\Test1.txt", true, Encoding.ASCII);
                //Writeout the numbers 1 to 10 on the same line.
                for(x=0; x < 10; x++)
                {
                    sw.Write(x);
                }
                //close the file
                sw.Close();
            }
            catch(Exception e)
            {
                Console.WriteLine("Exception: " + e.Message);
            }
            finally
            {
                Console.WriteLine("Executing finally block.");
            }
        }
    }
}

疑難排解

針對所有檔案操作,好的程式設計做法是把程式碼包裝在 try-catch-finally 區塊內,以便處理錯誤和例外狀況。 具體說來,您可能會想要在最後一個區塊中釋放檔案的控制代碼,以便檔案不致於無限期鎖定。 某些可能的錯誤包括不存在的檔案,或使用中的檔案。