Reputation: 617
I have written a short method that reads lines from a CSV file and builds a patient out of the column values. However it doesn't seem to like it when the column data isn't there and throws an "index out of range exception". I understand this is because the array value for that row is 0 but this could vary. How do I get around this?
I've tried checking if the length of the array was over 0 before it created the object which worked but it threw the exception again when the array only found one column in a row.
Here is my method which accepts a file path:
public static List<PatientObject> SplitFiles(String file)
{
List<PatientObject> PatientList = new List<PatientObject>();
var reader = new StreamReader(File.OpenRead(file));
while (!reader.EndOfStream)
{
var line = reader.ReadLine();
var values = line.Split('|');
PatientList.Add(new PatientObject(values[0], values[1], values[2], values[3], values[4], values[5], values[6], values[7], values[8], values[9], values[10], values[11], values[12], values[13], values[14], values[15], values[16], values[17]));
}
return PatientList;
}
Thanks in Advance
Upvotes: 0
Views: 2421
Reputation: 1181
I suggest you to use "??" operator for every field like this (of course, if you do not want to use the solution suggested by @fvu):
PatientList.Add(new PatientObject(values[0] ?? "", values[1] ?? "", values[2] ?? "", values[3] ?? "", values[4] ?? "", values[5] ?? "", values[6] ?? "", values[7] ?? "", values[8] ?? "", values[9] ?? "", values[10] ?? "", values[11] ?? "", values[12] ?? "", values[13] ?? "", values[14] ?? "", values[15] ?? "", values[16] ?? "", values[17] ?? ""));
Upvotes: 0
Reputation: 32973
As you are doing no check whatsoever on how many fields you actually get it will of course crash when there aren't at least 18 values in a line. The best solution depends on you exact situation, but here are some possible approaches:
EDIT: you could also switch to an existing CSV reading library. I've used A Fast CSV Reader with success, if offers several solutions for missing field scenarios.
Upvotes: 2