使用 Visual c # 讀取及寫入文字檔
本文可協助您使用 Visual c # 讀取及寫入文字檔。
原始產品版本: Visualstudio
原始 KB 編號: 816149
摘要
本文的「讀取文字檔」一節說明如何使用 StreamReader
類別來讀取文字檔。 寫入文字檔(範例1)和寫入文字檔(範例2)區段說明如何使用 StreamWriter
類別將文字寫入檔案。
讀取文字檔
下列程式碼會使用 StreamReader
類別來開啟、讀取及關閉文字檔。 您可以將文字檔的路徑傳遞至 StreamReader
建構函式,以自動開啟檔案。 ReadLine
方法會讀取每一行文字,並在讀取時,將檔指標增加至下一行。 當 ReadLine
方法到達檔結尾時,會傳回 null 參照。 如需詳細資訊,請參閱StreamReader 類別。
在 [記事本] 中建立範例文字檔。 請遵循下列步驟:
- 在 [記事本] 中貼上 hello world文字。
- 將檔案儲存為Sample.txt。
啟動 Microsoft Visual Studio。
在 [檔案] 功能表上,指向 [新增],然後選取 [專案]。
選取 [專案類型] 底下的Visual c # 專案,然後選取 [範本] 底下的 [主控台應用程式]。
在Class1.cs檔案的開頭新增下列程式碼:
using System.IO;
將下列程式碼新增至
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 lie 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."); }
在 [調試] 功能表上,選取 [開始] 以編譯及執行應用程式。 按 ENTER 鍵以關閉主控台視窗。 主控台視窗會顯示Sample.txt檔的內容:
Hello world
寫入文字檔(範例1)
下列程式碼會使用 StreamWriter
類別來開啟、寫入及關閉文字檔。 以類似的方式 StreamReader
,您可以將文字檔的路徑傳遞給 StreamWriter
建構函式,以自動開啟檔案。 方法會將 WriteLine
一整行文字寫入文字檔。
啟動 Visual Studio。
在 [檔案] 功能表上,指向 [新增],然後選取 [專案]。
選取 [專案類型] 底下的Visual c # 專案,然後選取 [範本] 底下的 [主控台應用程式]。
在Class1.cs檔案的開頭新增下列程式碼:
using System.IO;
將下列程式碼新增至
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."); }
在 [調試] 功能表上,選取 [開始] 以編譯及執行應用程式。 這段程式碼會在 [記事本] 之類的文字編輯器(例如 [記事本])中,建立名為Test.txt Test.txt的檔案。 Test.txt包含兩行文字:
Hello World!! From the StreamWriter class
寫入文字檔(範例2)
下列程式碼會使用 StreamWriter
類別來開啟、寫入及關閉文字檔。 與上一個範例不同的是,此程式碼會將兩個額外的參數傳遞至建構函式。 第一個參數是檔案路徑和檔案的檔案名。 第二個參數, true
指定以 append 模式開啟檔案。 如果您 false
為第二個參數指定,則每次執行程式碼時,會覆寫該檔案的內容。 第三個參數 Unicode
會指定,因此會 StreamWriter
以 Unicode 格式對檔進行編碼。 您也可以指定下列第三個參數的編碼方法:
- ASC11
- Unicode
- UTF7
- UTF8
Write
方法類似于 WriteLine
方法,但 Write
方法不會自動嵌入回車符或分行符號(CR/LF)字元組合。 當您一次只撰寫一個字元時,它會很有用。
啟動 Visual Studio。
在 [檔案] 功能表上,指向 [新增],然後按一下 [專案]。
按一下 [專案類型] 下的 [ Visual c # 專案],然後按一下 [範本] 底下的 [主控台應用程式
在Class1.cs檔案的開頭新增下列程式碼:
using System.IO; using System.Text;
將下列程式碼新增至
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."); }
在 [調試] 功能表上,選取 [開始] 以編譯及執行應用程式。 這段程式碼會在 [記事本] 之類的文字編輯器(例如 [記事本])中,建立名為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 lie 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
以處理錯誤和例外狀況。 具體說來,您可能會想要在最後一個區塊中釋放檔案的控點,使檔案不會無限期鎖定。 某些可能的錯誤包括不存在的檔案,或已在使用中的檔案。