从CSV文件读取时索引超出范围异常 [英] Index out of range exception when reading from CSV file
问题描述
大家好,
有人可以告诉我为什么我的索引超出了范围异常并带有以下代码。
想法是我想读取CSV文件并将内容输出到ListView中。第1列,第2列和第3列始终是数据,第4列是注释,因此不包含数据,而是我的'if(data [3]!= null)''。
如果我确保CSV中的所有列都有数据,并删除if语句,没问题!我显然在某个地方犯了一个小学生的错误。有人想告诉我在哪里吗? :)
Hi people,
Can somebody please tellme why i''m getting an Index out of range exception with the following code.
The idea is that i want to read a CSV file and output the contents into a ListView. Columns 1, 2 and 3 are always data, column 4 is for notes and therefore does not alwasy contain data, hense my ''if (data[3] != null)''.
If i make sure all columns in the CSV have data, and remove the if statement, no problems! I''m clearly making a schoolboy error somewhere. Anybody like to show me where? :)
public void readFromCSV()
{
using (FileStream fs = new FileStream("O:\\TestDaws\\CSDB\\Test2.csv", FileMode.Open, FileAccess.Read))
{
using (TextReader sr = new StreamReader(fs))
{
string line;
while ((line = sr.ReadLine()) != null)
{
string[] data = line.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries);
ListViewItem lvi = new ListViewItem();
lvi.Text = data[0];
lvi.SubItems.Add(data[1]);
lvi.SubItems.Add(data[2]);
if (data[3] != null) //Index out of range exception thrown here!
{
lvi.SubItems.Add(data[3]);
}
listView1.Items.Add(lvi);
}
}
}
}
推荐答案
它抛出因为你试图检查一个不存在的值而导致错误!而不是
It throws an error because you are trying to check a value that doesn''t exist! Instead of
if (data[3] != null)
尝试
Try
if (data.Length >= 4)
这篇关于从CSV文件读取时索引超出范围异常的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!