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

前端 未结 3 1278
闹比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:04

    I'm sorry but I see no problem with the way you are doing it though. I couldn't add comment.

    So just for the sake of answering, you probably could have try to call ReadLine() once before the loop. Might not be the best way as I don't know whats the behavior of running ReadLine() if its already end of stream, but it nothing is gonna happen then thats gonna save you some checks.

    Updated:

    To give a more complete answer, calling ReadLine() when the stream is at its end will return a null.

    Reference: http://msdn.microsoft.com/en-us/library/system.io.streamreader.readline.aspx

    Remember to check the return for null value.

    0 讨论(0)
  • 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<string> 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(',');
        ...
    }
    
    0 讨论(0)
  • 2021-01-14 16:14

    Could you not just read the first line outside of the loop without assigning it to a variable?

    using (StreamReader sr = new StreamReader(varFile, Encoding.GetEncoding(1250))) {
                string[] stringSeparator = new string[] { "\",\"" };
                if (!sr.EndOfStream)
                    sr.ReadLine();
                while (!sr.EndOfStream) {                    
                    string line = sr.ReadLine(); //.Trim('"');
                    string[] values = line.Split(stringSeparator, StringSplitOptions.None);
    
                    for (int index = 0; index < values.Length; index++) {
                        MessageBox.Show(values[index].Trim('"'));
                    }
                }
            }
    
    0 讨论(0)
提交回复
热议问题