格式化的文本文件,如何我完成解析它更新文件? [英] Formatting a text file, how to update the file after I finished parsing it?

查看:180
本文介绍了格式化的文本文件,如何我完成解析它更新文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

这篇关于格式化的文本文件,如何我完成解析它更新文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆