如何使用streamreader读取csv时跳过第一行

我有以下代码从csv文件中读取值并进行一些处理。 我想跳过输入csv文件的第一行,因为它包含头文本,但我想在处理完成后将其添加回去。

List values = new List(); using (StreamReader sr = new StreamReader(filePath)) { while (sr.Peek() != -1) { string line = sr.ReadLine(); List 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 

在进入循环之前先阅读它。 我这样做:

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

(我个人不喜欢使用Peek。)

然后在写出输出时,从headerLine开始。

只需阅读第一行,不做任何事……

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

像这样的东西:

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

您可以在while循环之前读取第一行并存储它,或者您可以使用计数器/布尔字段来检查文件中的位置。