格式化的文本文件,如何我完成解析它更新文件?

问题描述:

我将如何打开一个文件,对文件进行一些正则表达式,然后保存文件?

How would I open a file, perform some regex on the file, and then save the file?

我知道我可以打开一个文件,一行读线,但我将如何更新文件的实际内容,然后保存文件?

I know I can open a file, read line by line, but how would I update the actual contents of a file and then save the file?

下面的方法将不管工作反正文件大小,也不会破坏原来的文件,如果完成之前该操作将失败:

The following approach would work regardless of file size, and will also not corrupt the original file in anyway if the operation would fail before it is complete:

string inputFile = Path.Combine(Environment.GetFolderPath(
        Environment.SpecialFolder.MyDocuments), "temp.txt");
string outputFile = Path.Combine(Environment.GetFolderPath(
        Environment.SpecialFolder.MyDocuments), "temp2.txt");
using (StreamReader input = File.OpenText(inputFile))
using (Stream output = File.OpenWrite(outputFile))
using (StreamWriter writer = new StreamWriter(output))
{
    while (!input.EndOfStream)
    {
        // read line
        string line = input.ReadLine();
        // process line in some way

        // write the file to temp file
        writer.WriteLine(line);
    }
}
File.Delete(inputFile); // delete original file
File.Move(outputFile, inputFile); // rename temp file to original file name