How to skip first line and start reading file from second line in C#

前端 未结 3 1279
闹比i
闹比i 2021-01-14 15:30

How to start reading file from 2nd line skipping 1st line. This seems to work but is it best way to do so?

            using (StreamReader sr = new StreamRea         


        
3条回答
  •  被撕碎了的回忆
    2021-01-14 16:11

    If the file is not very large and can fit in memory:

    foreach (var line in File.ReadAllLines(varFile, Encoding.GetEncoding(1250)).Skip(1))
    {
        string[] values = line.Split(',');
        ...
    }
    

    If not write an iterator:

    public IEnumerable ReadAllLines(string filename, Encoding encoding)
    {
        using (var reader = new StreamReader(filename, encoding))
        {
            string line;
            while ((line = reader.ReadLine()) != null)
            {
                yield return line;
            }
        }
    }
    

    and then consume it:

    foreach (var line in ReadAllLines(varFile, Encoding.GetEncoding(1250)).Skip(1))
    {
        string[] values = line.Split(',');
        ...
    }
    

提交回复
热议问题