C#读取文件内容、替换某些内容并最终将其加载为XDocument的最有效方法
我想阅读文件内容并对其进行一些替换。之后,包含替换项的初始文件将作为XDocument加载。我做了两个不同的实现: 实施1:C#读取文件内容、替换某些内容并最终将其加载为XDocument的最有效方法,c#,xml,C#,Xml,我想阅读文件内容并对其进行一些替换。之后,包含替换项的初始文件将作为XDocument加载。我做了两个不同的实现: 实施1: string contents1 = File.ReadAllText(fileInfo.FullName, new UTF8Encoding(true)); File.WriteAllText(fileInfo.FullName, methodForReplacements(contents1), new UTF8Encoding(true)); return XD
string contents1 = File.ReadAllText(fileInfo.FullName, new UTF8Encoding(true));
File.WriteAllText(fileInfo.FullName, methodForReplacements(contents1), new UTF8Encoding(true));
return XDocument.Load(fileInfo.FullName, LoadOptions.PreserveWhitespace);
实施2:
string contents;
using (FileStream fs = File.OpenRead(fileInfo.FullName))
{
using (StreamReader sr = new StreamReader(fs, new UTF8Encoding(true)))
{
contents = methodForReplacements(sr.ReadToEnd());
}
}
using (StreamWriter sw = new StreamWriter(fileInfo.Name, false, new UTF8Encoding(true)))
{
sw.Write(contents);
}
return XDocument.Load(fileInfo.FullName, LoadOptions.PreserveWhitespace);
replacementMethod():
经过一些基准测试(10000次迭代,文件大小:265KB,numberOfReplacements:10),这两个实现的执行时间似乎非常相同(实现1:99秒,实现2:97秒)。有没有其他更优化、更有效的方法来实现相同的输出?它看起来像一个三任务块流程。所以,只要您不需要提前阅读,就可以知道必须在XDocument中写入哪些内容,您可以做的是在读取输入文件的每一行时,查找需要替换的字符,然后写出带有更改的输入行。在输入行和更改的内容之间,我想您有足够的信息和内容来决定哪些内容需要转到XDocument进行相应的响应。这将为您节省一些时间。看看这篇文章,它可能会有所帮助:根据aurhor的发现,普通读取器和缓冲读取器之间没有太大区别。
private string methodForReplacements(string contents)
{
string replaced = new StringBuilder(contents)
.Replace("\r", "
")
.Replace("\n", "
")
.ToString();
return replaced;
}