2012-07-26 16 views
1

我想修改以下代碼以處理大文件。如何修改SearchAndReplace例程以處理大文件

public static void Replace(string filePath, string searchText, string replaceText) 
    { 
     StreamReader reader = new StreamReader(filePath); 
     string content = reader.ReadToEnd(); 
     reader.Close(); 

     content = Regex.Replace(content, searchText, replaceText); 

     StreamWriter writer = new StreamWriter(filePath); 
     writer.Write(content); 
     writer.Close(); 
    } 

我在想,我會需要打開一個文件流寫入到一個新的文件名,然後刪除原始文件,並用新的替換它,當我完成了。那個聽起來是對的嗎?

另外... 我喜歡這個例程的簡單性,除了必要的文件I/O代碼行之外,只有一行代碼來處理文件。然而,我也想知道如果我爲了簡單而犧牲性能......是Regex.Replace非常高性能?

回答

1

首先:你可以嘗試Regex with Stream(似乎是更快速,更少的內存要求):

或看到Mono-Project Regex。它有流媒體的正則表達式。

看到這篇文章的正則表達式的性能:

,或者使用Regex是沒有必要使用String.Replace並嘗試這一行代碼:

File.WriteAllText(filePath, 
        File.ReadAllText(filePath).Replace(searchText, replaceText)); 
+0

是不是ReadAllText去讀整個文件到內存做沒有正則表達式?這個問題的主要部分是關於修改這個以處理大文件,因爲我得到一個內存異常,試圖一次加載整個文件。 – 2012-07-26 06:15:48

+0

@BrandonMoore:我也建議'正則表達式與流' – Ria 2012-07-26 06:19:31

1

你可以加速正則表達式的一種方法是pa使用RegexOptions.Compiled選項,該選項將採用您的正則表達式並將狀態機編譯爲IL。這對編譯步驟有一些開銷,但一旦編譯完成,正則表達式就會執行得更快。顯然你應該計算你的代碼,看看正則表達式編譯是否有助於或傷害你的場景。

0

你也能使用File

public static void Replace(string filePath, string searchText, string replaceText) 
{ 
    string newText = File.ReadAllText(filePath).Replace(searchText, replaceText)); 
    File.Delete(filePath); 
    File.WriteAllText(newFilePath, newText); 
} 
+0

你可能忽略了主要問題,那就是我需要這個來處理大文件。 ReadToEnd給我一個內存異常,我猜ReadAllText會做同樣的事情。 – 2012-07-26 06:14:09

+0

@BrandonMoore試試這個,否則我會給你另一個解決方案,一次不會消耗大量的內存 – HatSoft 2012-07-26 06:26:57

相關問題