2017-01-30 182 views
-1

首先,我對編碼和初學者級別的c#都非常熟悉。我看着這些問題,但無法找到適合我的問題的答案或者不明白。在c#中用streamreader讀取.csv文件#

我有一個.csv文件,文件中的行如下所示。我通過使用float longitude = float.Parse(read[1]);得到經度值,但我也想在下面的例子中得到數字「3」。在我看來,我可以通過使用float.Parse(read[12])來獲得價值。這個數字是該行的第12個指數。但我無法使用float.Parse(read[12])來達到這個數字。當我使用float.Parse(read[9])我可以得到3.此代碼不讀取逗號之間的缺失值。我如何讀取包含缺失值的所有數據?因爲其他線條不同而且缺失值正在改變。某些行不包含日期信息,其中一些不包含經度信息。

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]); 
} 
+3

_「這個代碼不讀逗號之間的遺漏值」 _ - 請閱讀[問]和[MCVE]和** **顯示相關的代碼。 – CodeCaster

+1

加入你如何得到你的''讀''' – Jacky

+0

StreamReader sr = new StreamReader(「Document path」); 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]); } – Burak

回答

2

此行

read = data.Split(seperators, StringSplitOptions.RemoveEmptyEntries); 

說:

如果有兩個逗號,一個接一個的權利,忽視入門

因此,您輸入變爲:

0000000,26.0000000,38.000000,30.01.2017,0,0,0,0,0,3,0,0,0,0

你真正想要的是什麼,這讓數組

read = data.Split(seperators, StringSplitOptions.None); 
+0

非常感謝您的幫助。 – Burak

0

錯誤的空值的這條線:

read = data.Split(seperators,StringSplitOptions.RemoveEmptyEntries); 

您正在告訴它刪除空值。你想要的失蹤者。 將其更改爲

read = data.Split(seperators,StringSplitOptions.None); 
+0

非常感謝您的幫助。 – Burak