2012-02-15 81 views
0

鑑於此代碼:處理的System.OutOfMemoryException

readFile = new FileStream(FilePath, FileMode.Open); 
streamReader = new StreamReader(readFile); 

dsSheet = new DataSet(); 
dsSheet.Tables.Add(sValidNumbersLibrary); 
dsSheet.Tables[sValidNumbersLibrary].Columns.Add("Numbers"); 
dt50Records = dsSheet.Tables[sValidNumbersLibrary].Clone(); 

String sLine = string.Empty; 
sLine = streamReader.ReadToEnd(); 
// The next line fails with System.OutOfMemoryException: 
sLine = (sLine.Contains(",")) ? sLine.Replace(",", "\r\n") : sLine; 
sLine = sLine.Replace("\r\n", ","); 

我應該如何處理這個System.OutOfMemoryException

+6

試試看?儘管如此,只是大塊閱讀。不要一次把它放在記憶中。 – jadarnel27 2012-02-15 16:28:03

+0

哪個喜歡導致異常? ReadToEnd? – 2012-02-15 16:28:13

+0

在此行上發生錯誤sLine =(sLine.Contains(「,」))? sLine.Replace(「,」,「\ r \ n」):sLine; – 2012-02-15 16:30:14

回答

0

我SLINE = streamReader.ReadToEnd後添加

streamReader.Dispose(); 

(); 這會在啓動替換過程之前釋放一些內存。

0

我同意,你應該閱讀數據塊文件先前的評論,但如果你必須閱讀整個塊到內存中一次:

與string.replace()是返回複製字符串的,所以在更換之後,你使用的內存是以前的兩倍。嘗試使用StringBuilder.Replace()來代替,或者如果您真的需要按下RAM,請將字符串加載到字節數組中,並以內聯方式操作字符串。 (雖然,因爲你用兩個替換一個字符,這會帶來一些問題。)

我要考慮它並重新訪問它。

0

一旦你完成了操作,你打算如何處理修改過的字符串?如果你只是將它寫入一個文件,那麼也許你應該一次讀一行,執行你的操作,然後把改寫的行寫入文件。 StreamReader的readline將返回所有內容,直到遇到\ r \ n。既然你打算用「,」替換\ r \ n,你可以在readline返回的字符串後加一個逗號。

using (StreamWriter sw = new StreamWriter(Path.GetTempFileName())) 
{ 
    using (StreamReader sr = new StreamReader(@"YourFile")) 
    { 
     while (!sr.EndOfStream) 
     { 
      string line = sr.ReadLine(); 
      if (line != null) 
      { 
       sw.Write(line + ","); 
      } 
     } 
    } 
} 

如果您在使用操作文本整個代碼的其餘部分,然後就可以構建的StringBuilder(與sb.Append替換sw.Write)字符串規劃;然而,使用StringBuilder並不能保證你不會遇到OutOfMemoryException。一個大字符串是一個大字符串。如果你的字符串沒有連續的內存塊,那麼你會得到這個OutOfMemoryException。另外,正如@SteveCzetty指出的那樣,你對string.Replace()的調用返回你的字符串的一個副本。字符串越大,你越有可能遇到異常。

相關問題