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());
}
}
}
}
我想从磁盘读取一个文本文件,在中间插入几行,然后将文件写入磁盘。考虑到这个操作要在一个 for each 循环中调用大约 1000 个文件,我发现这种方法效率很低。有没有更好的解决方案。提前致谢。