2012-02-01 108 views
17

我有我的以下代碼來讀取csv文件中的值並做一些處理。我想跳過輸入csv文件的第一行,因爲它包含標題文本,但我想在處理完成後將其添加回來。如何使用流讀取器讀取csv時跳過第一行

List<string> values = new List<string>(); 
using (StreamReader sr = new StreamReader(filePath)) 
{ 
    while (sr.Peek() != -1) 
    { 
     string line = sr.ReadLine(); 
     List<string> lineValues = line.Split(',').ToList(); 
     var tempMinInt = 1; 
     var tempValue = 1; 
     var tempValInt = Convert.ToInt32(lineValues[4]); 
     if (lineValues[3] == "1876") 
     { 
      if (tempValInt % 60 != 0) 
      { 
       tempMinInt = (tempValInt/60) + 1; 
       tempValue = tempMinInt * 30; 
      } 
      else 
      { 
       tempMinInt = tempValInt/60; 
       tempValue = tempMinInt * 30; 
      } 
     } 
     else if (lineValues[3] == "1875") 
     { 
      if (tempValInt != 0) 
      { 
       tempValue = 500; 
      } 
      else 
       tempValue = 0; 
     } 

     if (lineValues[3] == "1876") 
     { 
      values.Add(string.Join(",", lineValues) + "," + "0" + "," + "30" + "," + tempValue.ToString()); 
     } 
     else if (lineValues[3] == "1875") 
     { 
      values.Add(string.Join(",", lineValues) + "," + "1" + "," + "500" + "," + tempValue.ToString()); 
     } 

    } 
} 

樣品輸入CSV看起來是這樣的:

id, datetime, msisdn, num, duration 
33083,2011-12-19 05:17:57+06:30,98590149,1875,258 
33084,2011-12-19 05:22:28+06:30,98590149,1875,69 
33085,2011-12-19 05:23:45+06:30,98590149,1875,151 
33086,2011-12-19 05:30:21+06:30,98590149,1875,58 
33087,2011-12-19 06:44:19+06:30,949826259,1875,66 

,我想有一個像這樣我的輸出:

id, datetime, msisdn, num, duration, type, ammount, total 
33083,2011-12-19 05:17:57+06:30,98590149,1875,258,1,500,500 
33084,2011-12-19 05:22:28+06:30,98590149,1875,69,1,500,500 
33085,2011-12-19 05:23:45+06:30,98590149,1875,151,1,500,500 
33086,2011-12-19 05:30:21+06:30,98590149,1875,58,1,500,500 

回答

39

最初只是讀它你進入循環前。我應該這樣做:

using (StreamReader sr = new StreamReader(filePath)) 
{ 
    string headerLine = sr.ReadLine(); 
    string line; 
    while ((line = sr.ReadLine()) != null) 
    { 
     ... 
    } 
} 

(我不喜歡使用窺視,個人)

然後,當你寫出來的輸出,開始headerLine

1

您可以在while循環之前讀取第一行並存儲它,或者可以使用counter/boolean字段來檢查文件中的位置。

11

剛剛看過的第一線,什麼也不做吧......

List<string> values = new List<string>(); 
using (StreamReader sr = new StreamReader(filePath)) 
{ 
    sr.ReadLine(); 
    while (sr.Peek() != -1) 
    { 
     string line = sr.ReadLine(); 
     List<string> lineValues = line.Split(',').ToList(); 

     //***// 
    } 
} 
3

事情是這樣的:

bool isFirst=true; 
using (StreamReader sr = new StreamReader(filePath)) 
{ 
    while (sr.Peek() != -1) 
    { 
     if(isFirst) 
     { 
      isFirst=false; 
      continue; 
     } 
    } 
}