C# How to skip number of lines while reading text file using Stream Reader?

前端 未结 6 1316
天命终不由人
天命终不由人 2020-12-05 18:50

I have a program which reads a text file and processes it to be seperated into sections.

So the question is how can the program be changed to allow the program to sk

6条回答
  •  甜味超标
    2020-12-05 19:15

    I'll add two more suggestions to the list.

    If there will always be a file, and you will only be reading, I suggest this:

    var lines = File.ReadLines(@"C:\Test\new.txt").Skip(5).ToArray();
    

    File.ReadLines doesn't block the file from others and only loads into memory necessary lines.

    If your stream can come from other sources then I suggest this approach:

    class Program
    {
        static void Main(string[] args)
        {
            //it's up to you to get your stream
            var stream = GetStream();
    
            //Here is where you'll read your lines. 
            //Any Linq statement can be used here.
            var lines = ReadLines(stream).Skip(5).ToArray();
    
            //Go on and do whatever you want to do with your lines...
        }
    }
    
    public IEnumerable ReadLines(Stream stream)
    {
        using (var reader = new StreamReader(stream))
        {
            while (!reader.EndOfStream)
            {
                yield return reader.ReadLine();
            }
        }
    }
    

    The Iterator block will automatically clean itself up once you are done with it. Here is an article by Jon Skeet going in depth into how that works exactly (scroll down to the "And finally..." section).

提交回复
热议问题