簡體   English   中英

C# 讀取文件內容、替換某些內容並最終將其加載為 XDocument 的最有效方法

[英]C# Most efficient way to read file content, replace some content and finally load it as XDocument

我想閱讀文件內容並對其進行一些替換。 之后,帶有替換的初始文件將作為 XDocument 加載。 我做了兩個不同的實現:

實施1:

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);

替換方法():

private string methodForReplacements(string contents)
{
    string replaced = new StringBuilder(contents)
        .Replace("\r", "
")
        .Replace("\n", "
")
        .ToString();

    return replaced;
}

經過一些基准測試(10000 次迭代,文件大小:265KB,numberOfReplacements:10),似乎 2 個實現的執行時間幾乎相同(實現 1:99 秒,實現 2:97 秒)。 有沒有其他更優化和更有效的方法來實現相同的輸出?

它看起來像一個三個任務塊的過程。 所以只要你不需要提前閱讀知道你必須插入XDocument,你可以做的就是在你閱讀輸入文件的每一行時,尋找需要替換的字符,然后寫入out 輸入行有變化。 在輸入行和更改的內容之間,我收集到您有足夠的信息和內容來決定需要轉到 XDocument 以進行相應響應的內容。 那會為你節省一些時間。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM