2011-10-07 23 views
0

下面的代码适用于处理1MB以下的CSV文件,但在尝试读取600MB文件时失败。任何理由?或者任何修复?对于大型650MB CSV文件,C#linq Files.ReadAllLines()失败

我想要做的是在Visual C#2010中读取一个大的原始CSV文件并操纵内容,可以一行一行地将内容一次性移动到内存中,并使用LINQ导出5个具有特定选择的文件。这5个文件将用于各种过程,因此需要将它们分成5个不同的文件,并且内容非常不同。

当文件很小时,代码可以很好地工作,但是当代码太大时,会给异常处理中的消息框“无法写入源目标”。我已经尝试了ReadAllLines()和ReadLines()请你能给我建议。谢谢。

public void button2_Click(object sender, EventArgs e) 
    { 

     string file_name = textBox1.Text.ToString(); 
     // Get the directories to split the file in. 
     string directoryPath = Path.GetDirectoryName(textBox1.Text.ToString()); 
     if (File.Exists(file_name) == true) 
     { 
      try 
      { 
       StreamReader readerfile = new StreamReader(file_name); 

       var BillSummaryQuery1 = 
        (from line in File.ReadAllLines(file_name) 
        let linerecord = line.Split(',').ToList() 
        select line).ToList(); 

       #region Start Writing BillSummary.CSV 


       //lines removed 

       #endregion End writing BillSummary.CSV 

       #region Start writing Notes.CSV 

       //lines removed 


       #endregion Notes.CSV 



       string message = 
         "Bill Translated Successfully! \r\nFiles located in: " + directoryPath; 
       MessageBox.Show(message, "Success", MessageBoxButtons.OK, MessageBoxIcon.Information); 

      } 

      catch (Exception) 
      { 
       string message2 = "Cannot write to source destination"; 
       MessageBox.Show(message2, "Error"); 



      } 


     } 
     else 
     { 
      MessageBox.Show("No such file exists","Error",MessageBoxButtons.OK,MessageBoxIcon.Error); 
     } 
+1

而不是你现在正在打印的信息,做“catch(Exception e)”并打印'e',然后通过编辑你的问题与我们分享那个异常信息。我猜你正在得到一个内存不足的例外,但没有例外输出,很难确定。此外,机器有多少内存? – mtijn

+0

我不知道那个例外的原因是什么。但是如果我必须处理一个650 MB的文件,我不会一次性将所有内容加载到内存中。使用'StreamReader'并使用'ReadLine'来获取行要好得多。 – Amry

+0

也必须同意@mtijn,正确捕捉异常并查看它是什么。 – Amry

回答

6

如果您正在使用StreamReader,为什么不使用它?

public void button2_Click(object sender, EventArgs e) 
{ 
    string file_name = textBox1.Text.ToString(); 
    // Get the directories to split the file in. 
    string directoryPath = Path.GetDirectoryName(textBox1.Text.ToString()); 
    if (File.Exists(file_name) == true) 
    { 
     try 
     { 
      using (StreamReader reader= new StreamReader(file_name)) 
      { 
       string line = null; 
       while ((line = reader.ReadLine()) != null) 
       { 
        // Do your stuff 
       } 
      } 
     } 

     catch (Exception ex) 
     { 
      Trace.TraceError(ex.Message); 
      string message2 = "Cannot write to source destination"; 
      MessageBox.Show(message2, "Error"); 
     } 
    } 
    else 
    { 
     MessageBox.Show("No such file exists", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error); 
    } 
} 
+1

或者,如果您使用.NET 4或更高版本,则可以使用'File.ReadLines'方法:http://msdn.microsoft.com/zh-cn/library/dd383503.aspx – LukeH