Search code examples
c#linestreamreader

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


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

How can the program be changed to allow the program to skip reading the first 5 lines of the file while using the Stream Reader to read the file?

The code:

class Program
{
    static void Main(string[] args)
    {
        TextReader tr = new StreamReader(@"C:\Test\new.txt");

        String SplitBy = "----------------------------------------";

        // Skip first 5 lines of the text file?
        String fullLog = tr.ReadToEnd();

        String[] sections = fullLog.Split(new string[] { SplitBy }, StringSplitOptions.None);

        //String[] lines = sections.Skip(5).ToArray();

        foreach (String r in sections)
        {
            Console.WriteLine(r);
            Console.WriteLine("============================================================");
        }
    }
}

Solution

  • Try the following

    // Skip 5 lines
    for(var i = 0; i < 5; i++) {
      tr.ReadLine();
    }
    
    // Read the rest
    string remainingText = tr.ReadToEnd();