2011-10-06 70 views
-5

可能重复:
use unassigned local variable 'multidimension'读取文件多维数组C#分裂

我得到一个错误,当我运行这个程序。代码所做的是从文本文件中读取行和句子之间用逗号隔开,我所做的是将它们拆分并放入多维数组中,但运行时出现错误:

"unhanded exception has occurred in your application if you click continue the application will ignore this error and attempt to continue if you click quit the application will close immediately" 

代码:

try { 
    DialogResult result = openFileDialog1.ShowDialog(); 
    if (result == DialogResult.OK) { 

     using (StreamReader sr = new StreamReader(openFileDialog1.FileName)) { 
      string[] data= null; 
      string ReadFromReadLine; 
      ReadFromReadLine = sr.ReadLine(); 
      string[,] multidimensional = new string[ReadFromReadLine.Length, data.Length]; 

      while (ReadFromReadLine != null) { 
       data = ReadFromReadLine.Split(','); 

       for (int i = 0; i <= ReadFromReadLine.Length; i++) { 
        for (int j = 0; j <= data.Length; j++) { 
         multidimensional[i, j] = data[j]; 
        } 
       }  
      } 

      for(int i = 0 ; i<ReadFromReadLine.Length;i++) { 
       for(int j = 1; j<= data.Length ; j++) { 
        textBox1.Text += multidimensional[i,j]; 
       } 
      } 
     } 
     FilePath.Text = openFileDialog1.FileName; 
     //textBox1.Text += (string)File.ReadAllText(FilePath.Text); 
    } 
} 
catch(IOException ex) { 
    MessageBox.Show("there is an error" + ex+ "in the file please try again"); 
} 
} 
+1

**你有什么例外**? _使用调试器!_ – SLaks

+0

@SLaks:这是他对[使用未分配的局部变量'multidimension'](http://stackoverflow.com/questions/7669026/use-unassigned-local-variable-multidimension)的后续。到目前为止,调试仍然存在四个问题。 – user7116

+0

您已发布三个关于同一问题的问题。这个答案:http://stackoverflow.com/questions/7669026/use-unassigned-local-variable-multidimension/7669130#7669130包含解决您的问题。主要问题是当你不知道你有多少行时,你正在尝试构建一个多维数组。他建议使用“列表”是一个很好的建议。 –

回答

1

的错误是在这里:

ReadFromReadLine = sr.ReadLine(); 
string[,] multidimensional = new string[ReadFromReadLine.Length, data.Length]; 

当遇到文件的末尾,ReadLine()回报null。然后第二行崩溃,因为ReadFromReadLine.Length无法计算。