在c#中有效地读取 - 修改 - 写入文本文件

时间:2013-08-02 12:49:10

标签: c# file-io

 private void AlterFile(string fileName)
    {
        StringBuilder content = new StringBuilder();
        bool isAltered = false;
        lock (LockObj)
        {
            using (StreamReader reader = new StreamReader(fileName))
            {
                string currLine;
                currLine = reader.ReadLine();
                while (currLine != null)
                {
                    content.AppendLine(currLine);
                    if (currLine.Contains(KeywordToSearch))
                    {
                        isAltered = true;
                        //insert data in string builder to be inserted here
                    }
                    currLine = reader.ReadLine();
                }


            }
            if (isAltered)
            {
                using (StreamWriter writer = new StreamWriter(fileName))
                {
                    writer.WriteLine(content.ToString());
                }
            }
        }
    }

我想从磁盘读取文本文件,在其间插入几行,然后将文件写入磁盘。考虑到这个操作是针对大约1000个文件的每个循环调用的,我觉得这种方式效率很低。 对此有更好的解决方案吗? 提前谢谢。

0 个答案:

没有答案