Read .csv file with streamreader in c#
First of all i'm very new with coding and at the beginner level in c#. I look at the questions but couldn't find proper answer for my question or didn't understand.
I have a .csv file and the lines in the files are like below. I get the longitude value by using float longitude = float.Parse(read[1]);
But I also want to get the number "3" in the example of below. In my opinion i can get the value by using float.Parse(read[12])
. This number is in the 12th index in the line. But i cannot reach that number by using float.Parse(read[12])
. When i use float.Parse(read[9])
i can get the 3. This code is not reading the missing values between commas. How can i read all the data incluiding missing values? Because the other lines are different and missing values are changing. Some of the line doesn't include date information, some of them doesn't include longitude information.
0000000,26.0000000,38.000000,30.01.2017,0,0,0,,,0,0,,3,,0,0,0,0
string[] read;
char[] seperators = { ',' };
StreamReader sr = new StreamReader("D:/xxx.csv");
string data = sr.ReadLine();
while ((data = sr.ReadLine()) != null)
{
read = data.Split(seperators,StringSplitOptions.RemoveEmptyEntries);
float longitude = float.Parse(read[1]);
float latitude = float.Parse(read[2]);
}
Solution 1:
This line
read = data.Split(seperators, StringSplitOptions.RemoveEmptyEntries);
Says:
If there are two commas, one right after the other, ignore the entry
Hence, your input becomes:
0000000,26.0000000,38.000000,30.01.2017,0,0,0,0,0,3,0,0,0,0
What you really want is this, which leaves empty values in the array
read = data.Split(seperators, StringSplitOptions.None);