本文帮助你使用 Visual C# 读取和写入文本文件。

原始产品版本: Visual Studio

原始 KB 数: 816149

总结

本文的读取文本文件部分介绍如何使用 StreamReader 类读取文本文件。 编写文本文件 (示例 1) 和编写文本文件 (示例 2) 部分StreamWriter介绍如何使用类将文本写入文件。

读取文本文件

以下代码使用StreamReader类打开、读取和关闭文本文件。 可将文本文件的路径传递给StreamReader构造函数,以自动打开该文件。 该方法ReadLine读取每行文本,并递增文件指针以在读取时指向下一行。 ReadLine当方法到达文件的末尾时,它将返回一个空引用。 有关详细信息,请参阅 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 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.");

}

在“调试”菜单上,选择“开始”以编译并运行应用程序。 按 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.");

}

在“调试”菜单上,选择“开始”以编译并运行应用程序。 此代码在驱动器 C 上创建名为 Test.txt 的文件。在文本编辑器中(如 Notepad)打开 Test.txt。 Test.txt 包含两行文本:

Hello World!!

From the StreamWriter class

编写一个文本文件(示例 2)

以下代码使用StreamWriter类打开、写入和关闭文本文件。 与上一示例不同,此代码将两个附加参数传递给构造函数。 第一个参数是文件路径和文件名。 第二个参数true指定在追加模式下打开文件。 如果指定false第二个参数,则每次运行代码时将覆盖文件的内容。 第三个参数指定Unicode,以便以StreamWriter Unicode 格式对文件进行编码。 还可以为第三个参数指定以下编码方法:

ASC11

Unicode

UTF-7

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.");

}

在“调试”菜单上,选择“开始”以编译并运行应用程序。 此代码在驱动器 C 上创建名为 Test1.txt 的文件。在文本编辑器上(如 Notepad)打开 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以处理错误和异常。 具体来说,你需要在最后一个块中释放文件的句柄,以便文件不会无限期锁定。 一些可能的错误包括不存在的文件或已在使用的文件。