简体   繁体   English

在C#中读取csv文件时,如何忽略csv文件中的第一行

[英]How to ignore the first line in a csv file when you read the csv file in C#

I now how to read a csv file in C#. 我现在如何在C#中读取csv文件。 For instance, the file data consists of three columns, you can make an array that has three columns and the number of rows does not matter since you can use, for instance a while loop that read the csv file until it gets null. 例如,文件数据由三列组成,您可以创建一个具有三列的数组,并且行数无关紧要,因为可以使用,例如while循环读取csv文件直到其为空。

I just want to know how not to read the first line of a csv file and read the rest of it. 我只想知道如何不读取csv文件的第一行并读取其余部分。 Sometimes data files such as .txt, .csv contains different types of data. 有时,.txt,.csv等数据文件包含不同类型的数据。 In a csv file, it might have "store catalog" in the first line as the title and then have a phone number, a owner name, a monthly sale in each line from the second line. 在csv文件中,第一行的标题可能具有“商店目录”,然后第二行的每一行都有电话号码,所有者名称和每月销售量。

It's going to end up looking something like. 最终看起来像这样。

reader.ReadLine();

var text = reader.ReadToEnd();

or you could do something like: 或者您可以执行以下操作:

var text = reader.ReadAllLines();
text = text.Skip(1);

This is all assuming you're using the built-in .NET readers, of course. 当然,所有这些都假设您正在使用内置的.NET阅读器。

One way, use File.ReadLines and Enumerable.Skip : 一种方法,使用File.ReadLinesEnumerable.Skip

IEnumerable<string> allButFirstLine = File.ReadLines(path).Skip(1);

If you want to know the difference between ReadAllLines and ReadLines read the remarks section. 如果您想了解ReadAllLinesReadLines之间的区别,请阅读备注部分。

If you are using a StreamReader , use ReadLine() and do nothing: 如果您使用StreamReader ,请使用ReadLine()执行任何操作:

using (var reader = new System.IO.StreamReader(path, encoding))
{
    // change numToSkip accordingly
    for (int i = 0; i < numToSkip; i++) 
        reader.ReadLine();  

    // ...

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM