This article is currently in the process of being translated into Chinese (~71% done).
Reading and writing files
本章介绍如何使用C#读写简单文件。幸好这对C#来说很简单。使用System.IO名空间的File类,读写文件所需的功能几乎都有了,让简单的读写文件操作变得非常容易。
第一个例子将创建一个极简单的文本编辑器。简单到只能读取一个文件,然后往里面写入新内容,且一次只能写入一行文本。但这展示了使用File类有多简单:
using System;
using System.IO;
namespace FileHandlingArticleApp
{
class Program
{
static void Main(string[] args)
{
if(File.Exists("test.txt"))
{
string content = File.ReadAllText("test.txt");
Console.WriteLine("Current content of file:");
Console.WriteLine(content);
}
Console.WriteLine("Please enter new content for the file:");
string newContent = Console.ReadLine();
File.WriteAllText("test.txt", newContent);
}
}
}本例中有三处使用了File类:使用其检查文件是否存在,使用其ReadAllText()方法读取文件内容,及使用其WriteAllText()方法把新内容写入文件。示例中没有使用绝对路径,只简单地使用了文件名。这会把生成的文件存到本程序执行文件所在的目录,目前这样就好。重点是示例要易于理解:先检查文件是否存在,若存在,读取其内容并输出到控制台。然后提示用户输入新内容,一旦程序获得了新内容,就把其写入文件。这显然会覆盖掉原有内容,不过目前这样就好。当然也可以换用AppendAllText方法。用其替换WriteAllText行代码试试:
File.AppendAllText("test.txt", newContent);再运行看看,新的文本被添加到了现有文本后面,而非覆盖原有内容。就这么简单。但每运行一次程序仍然只能得到一行文本。下面增加些创意,继续改造此示例。把代码的最后几行作如下修改:
Console.WriteLine("Please enter new content for the file - type exit and press enter to finish editing:");
string newContent = Console.ReadLine();
while(newContent != "exit")
{
File.AppendAllText("test.txt", newContent + Environment.NewLine);
newContent = Console.ReadLine();
}新代码让用户输入单词exit来结束文件编辑,否程序就会持续地把用户输入写入文件,然后再提示用户输入新内容。写入时还在后面加入了一个换行符Environment.NewLine,让其成为真正的文本行。
不过,除了每次都做写入文件的操作,还有更好的方法,类似这样:
Console.WriteLine("Please enter new content for the file - type exit and press enter to finish editing:");
using(StreamWriter sw = new StreamWriter("test.txt"))
{
string newContent = Console.ReadLine();
while(newContent != "exit")
{
sw.Write(newContent + Environment.NewLine);
newContent = Console.ReadLine();
}
}使用流(Streams)操作有点超出本章内容,但把其用在本例中是非常适合的,因为只需打开一次文件,然后结束时内容会被自动写入文件。本例使用了C# using()表达式的功能,以保证文件引用在代码离开本作用域时被关闭,即在代码块的结束位置 { }。如果没有使用using()表达式,就必需调用StreamWriter实例的Close()方法来关闭文件引用。