读取文件多维数组c#split

时间:2011-10-06 00:04:57

标签: c# multidimensional-array split

  

可能重复:
  use unassigned local variable 'multidimension'

运行此程序时出错。代码所做的是从文本文件中读取的行和句子是用逗号分隔的,我所做的是拆分它们并将它们放在多维数组中但是我在运行时遇到错误:

"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 个答案:

答案 0 :(得分:1)

错误在于:

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

遇到文件结尾时,ReadLine()会返回null。然后第二行崩溃,因为无法计算ReadFromReadLine.Length