Bradley
Bradley

Reputation: 617

Reading a CSV file and getting an index out of range exception on different sized rows

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

Answers (2)

Serge Velikan
Serge Velikan

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

fvu
fvu

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:

  • at the very least you should probably skip the line when there are not >= 18 elements in the row - you should probably log the fact that you skipped them, to avoid later confusion.
  • if there are less than 18 elements, it may be possible to feed default values to the database, or values that indicate that there was no input for that field.

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

Related Questions