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]);
}
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);
The error is this line:
read = data.Split(seperators,StringSplitOptions.RemoveEmptyEntries);
You are telling it to remove the empty values. The missing ones you want. Change it to
read = data.Split(seperators,StringSplitOptions.None);
As others mentioned you must change StringSplitOptions.RemoveEmptyEntries
to StringSplitOptions.None
.
However, since this is the default parameter you can simply use:
read = data.Split(seperators);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.