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个文件的每个循环调用的,我觉得这种方式效率很低。 对此有更好的解决方案吗? 提前谢谢。