我没有写任何数组长度但是当我尝试读取.csv文件时,我得到“索引超出了数组的范围”错误。 .csv文件大约是1 000 000行。有人修这个代码吗?
.csv文件行如下所示。
0000000,26.0000000000000,38.0000000000000,30.01.2017,0,0,0,,,0,0,,0,,0,0,0,0
string[] read;
char[] seperators = { ',' };
try
{
Image img = Image.FromFile(txtFilePath.Text);
Graphics g = Graphics.FromImage(img);
pictureBox1.Image = img;
pictureBox1.SizeMode = PictureBoxSizeMode.StretchImage;
StreamReader sr = new StreamReader(txtFile2Path.Text);
string data;
while ((data=sr.ReadLine()) !=null)
{
read = data.Split(seperators, StringSplitOptions.None);
float x = float.Parse(read[1]);
float y = float.Parse(read[2]);
string z = read[10];
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
只是为了澄清那些最终在这里的人的答案..
while ((data=sr.ReadLine()) !=null)
{
read = data.Split(seperators, StringSplitOptions.None);
if (read.Length >= 11)
{
float x = float.Parse(read[1]);
float y = float.Parse(read[2]);
string z = read[10];
}
}
访问可能不是所需长度的阵列时,请先检查它。
只有当一行代码试图访问不存在的数组中的项目(N-1)时才会抛出Index was outside the bounds of the array
异常 - 因为该数组具有少于(N)个项目