我正在尝试从csv文件中读取数据:
private static void ReadAnimalData(string file, Dictionary<string, Branch> branches)
{
string town = null;
using (StreamReader reader = new StreamReader(@file))
{
string line = null;
line = reader.ReadLine();
if (line != null)
{
town = line;
}
Branch branch = branches[town];
while (null != (line = reader.ReadLine()))
{
string[] values = line.Split(',');
char type = Convert.ToChar(line[0]);
string name = values[1];
int chipId = int.Parse(values[2]);
string breed = values[3];
string owner = values[4];
string phone = values[5];
DateTime vd = DateTime.Parse(values[6]);
Console.WriteLine(type);
switch (type)
{
case 'D':
bool aggressive = bool.Parse(values[7]);
Dog dog = new Dog(name, chipId, breed, owner, phone, vd, aggressive);
branch.Dogs.Add(dog);
break;
case 'C':
Cat cat = new Cat(name, chipId, breed, owner, phone, vd);
branch.Cats.Add(cat);
break;
}
}
}
}
数据文件:
Kaunas
D,Reksas,823,Buldogas,Jonas,867424992,2015-07-24,TRUE
C,Morkus,658,Siamo,Antanas,865412654,2014-11-24
D,Keksas,456,Taksas,Petras,866612345,2014-12-01,FALSE
...
但是,以下代码不起作用。它按预期读取第一行,但读取第二行会导致错误(IndexOutOfRangeExeption
)。发生错误是因为某些原因reader.ReadLine()
将该行读为""
。可能是造成这个问题的原因是什么?