读取文件多维数组c#split



可能重复:
使用未分配的局部变量';多维';

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

"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");
}
}

错误在这里:

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

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

相关内容

  • 没有找到相关文章

最新更新