2015-09-01 82 views
-2

我嘗試使用「|」讀取文本文件數據,分開,我使用下面的代碼。試圖把數據表中的數據到數據視圖我m到處類型的異常時,我爲能夠讀取後,讀取文本文件中的數據「System.OutOfMemoryException的」被拋出,從文本文件讀取數據時拋出類型'System.OutOfMemoryException'的異常

任何一個可以建議我如何避免此異常。

string filepath = System.Configuration.ConfigurationManager.AppSettings["data"]; 

if (filepath != "") 
      { 
       DataTable dt = new DataTable("file"); 
       string[] columns1 = null; 
       var lines = File.ReadAllLines(filepath); 
       int Count = lines.Length; 
       //here taking columns and adding to table 
       if (lines.Count() > 0) 
       { 
        columns1 = lines[0].Split(new char[] { '|' }); 
        foreach (var column in columns1) 
         dt.Columns.Add(column); 
       }     
       for (int i = 1; i < lines.Count(); i++) 
       { 
        DataRow dr = dt.NewRow(); 
        string[] values = lines[i].Split(new char[] { '|' }); 
        for (int j = 0; j < values.Count() && j < columns1.Count(); j++) 
        { 
         dr[j] = values[j]; 
        } 

       } 
       dt.Rows.Add(dr); 

        DataView View = new DataView(dt); 
        //Here I m getting "Exception of type 'System.OutOfMemoryException' was thrown." 
        DataTable MD = View.ToTable("MD", false, "ID", "Description") 
        DataTable MM = View.ToTable("MM", false, "RecordNumber", "Item description") 
       if (MD.Rows.Count > 0) 
       { 
        InsertData(MD); 
       } 
       if (MM.Rows.Count > 0) 
       { 
        InsertData1(MM); 
       } 
      } 

堆棧跟蹤: - String.Split的

at System.Collections.Generic.List`1.set_Capacity(Int32 value) 
    at System.Collections.Generic.List`1.EnsureCapacity(Int32 min) 
    at System.Collections.Generic.List`1.Add(T item) 
    at System.Data.DataView.ToTable(String tableName, Boolean distinct, String[] columnNames) 
+2

什麼是一個文件的大小? – wudzik

+0

異常行(完整跟蹤)。該問題很可能是文件大小,或文件中的條目數超過了列表中允許的最大條目數。 – Kilazur

+0

我試圖讀取有5記錄的文本文件。 –

回答

0

多種用途,也容易造成一個OutOfMemoryException。下載Lumenworks Fast CSV Reader - 問題解決了。您將在這裏得到它:http://www.codeproject.com/Articles/9258/A-Fast-CSV-Reader

有關與分割問題的更多細節,看看下面的鏈接:

http://vpnchoudhary.blogspot.ie/2011/03/out-of-memory-exception-simple.html

string.split() "Out of memory exception" when reading tab separated file

相關報價這裏:

當您對包含1355049逗號的字符串進行拆分時會發生什麼情況 分隔16個字符的字符串每個字母,總字符長度爲 的25745930?

指針字符串對象的數組:連續虛擬地址4(地址指針)的 空間* 1355049 = 5420196(數組大小)+ 16(對於 記賬)= 5420212.用於 非連續虛擬地址空間1355049個字符串,每個54個字節。這並不意味着所有這些1.3 的字符串將散佈在整個堆中,但它們將不會被分配在LOH上。 GC會將它們分配到Gen0 堆上的簇中。 Split.Function將創建System.Int32 []的 大小25745930的內部陣列,消耗(102983736個字節)〜LOH的98MB,這是非常昂貴 L.

+0

「多次使用String.Split可能會導致OutOfMemoryException。」 - 如果你要這樣做,你真的應該引用你的消息來源。 – theB

+0

我提供了一個編輯 - 請刪除您的downvote。 – GinjaNinja

相關問題