C# 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 seperated into sections.

So the question is 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?

Could someones please advise on the codes? Thanks!

The Codes:

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("============================================================");
        }
    }
}

Try the following

// Skip 5 lines
for(var i = 0; i < 5; i++) {
  tr.ReadLine();
}

// Read the rest
string remainingText = tr.ReadToEnd();

Skip Reading Specific Number Of Lines (Using StreamReader), How do I skip line starting with # when reading "streamreader"a text file? RRS feed � Visual Studio Languages. , .NET Framework. > Visual C#. 2 minutes to read +7; In this article. This example reads the contents of a text file, one line at a time, into a string using the ReadLine method of the StreamReader class. Each text line is stored into the string line and displayed on the screen. Example int counter = 0; string line; // Read the file and display it line by line.

If the lines are fixed then the most efficient way is as follows:

using( Stream stream = File.Open(fileName, FileMode.Open) )
{
    stream.Seek(bytesPerLine * (myLine - 1), SeekOrigin.Begin);
    using( StreamReader reader = new StreamReader(stream) )
    {
        string line = reader.ReadLine();
    }
}

And if the lines vary in length then you'll have to just read them in a line at a time as follows:

using (var sr = new StreamReader("file"))
{
    for (int i = 1; i <= 5; ++i)
        sr.ReadLine();
}

How do I skip line starting with # when reading "streamreader"a text , In this tutorial, you will learn how to use the StreamReader object to Rather, in order to read a specific line number of a text file or stream, To read a specific line, you can invoke ReadLine() for each line you need to skip. In a while loop, we read the contents of the file line by line with the StreamReader's ReadLine() method. C# read text file asynchronously with StreamReader's ReadToEndAsync The ReadToEndAsync() method reads all characters from the current position to the end of the stream asynchronously and returns them as one string.

If you want to use it more times in your program then it maybe a good idea to make a custom class inherited from StreamReader with the ability to skip lines.

Something like this could do:

class SkippableStreamReader : StreamReader
{
    public SkippableStreamReader(string path) : base(path) { }

    public void SkipLines(int linecount)
    {
        for (int i = 0; i < linecount; i++)
        {
            this.ReadLine();
        }
    }
}

after this you could use the SkippableStreamReader's function to skip lines. Example:

SkippableStreamReader exampleReader = new SkippableStreamReader("file_to_read");

//do stuff
//and when needed
exampleReader.SkipLines(number_of_lines_to_skip);

StreamReader Read Specific Line, Read text files with StreamReader inside a using-statement. The StreamReader will free resources on its own. string line; using (StreamReader reader = new� In this tutorial, you will learn how to use the StreamReader object to read a specific line number of a text file in your C# applications. Recall that StreamReader can be used to read the contents of a text file in C#. The class has methods for reading individual characters, reading to the end of the file, and for reading individual lines.

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<string> 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).

C# StreamReader Examples, Nov 29, 2017 � 4 min read i) minimize the amount of used memory and For the sake of the argument, we could use StreamReader , but that would lead to write Takes a text file as input where each line is an integer; Calculates the sum of all the For the sake of this example, we'll skip pretty validation messages :-) In� Stream.Reader.Peek() method checks if there are more characters are left to read in a file. The method returns an integer. If the value is less than 0, there are no more characters left to read. The following code snippet uses the Peak() method to check if there are more characters left to read in a file.

I'd guess it's as simple as:

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

        var SplitBy = "----------------------------------------";

        // Skip first 5 lines of the text file?
        foreach (var i in Enumerable.Range(1, 5)) tr.ReadLine();
        var 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("============================================================");
        }
    }

C#: File.ReadLines() vs File.ReadAllLines() — and why , The simplest way to get the number of lines in a text file is to combine is new- up a StreamReader and yield return every line read from the file� C# program that reads all lines using System; using System.Collections.Generic; using System.IO; class Program { static void Main() {// // Read in a file line-by-line, and store it all in a List.

Counting Lines of a Text File in C#, the Smart Way, Text; using System. The streamreader was able to navigate to line 872 in less than a second. 1 In addition, if you know each of these files will contain a certain block size (number of bytes) that you always want to skip, you� Imports System.IO Class Test Public Shared Sub Main() Try ' Create an instance of StreamReader to read from a file. Dim sr As StreamReader = New StreamReader("TestFile.txt") Dim line As String ' Read and display the lines from the file until the end ' of the file is reached.

Reading Lines (Skip to a certain line#) [SOLVED], string strLine = string.Empty; string strFile = @"c:\Achdemo.txt"; ArrayList arr = new ArrayList(); StreamReader sr = new StreamReader(strFile); If the current method throws an OutOfMemoryException, the reader's position in the underlying Stream object is advanced by the number of characters the method was able to read, but the characters already read into the internal ReadLine buffer are discarded. If you manipulate the position of the underlying stream after reading data into the

How to skip the first line from a text file, There are several ways to read contents of a file line by line in C#. The following code opens the text file using a stream reader, copies the contents to a string,� I have my following code to read values from csv file and do some processing. I would like to skip the first row of the input csv file as it contains header text but I'd want to add it back after the processing is done.

Comments
  • so whats the issue with using commented out line?
  • Its to show experts that .split method does not work.
  • possible duplicate of C# How to skip lines in Text file after text coverted to array?
  • How does the Split() not work? It is very suboptimal on large files of course, but it is functional.
  • Just a note, unlike the other solutions here this will not bother reading the lines you're skipping over, and should be much faster than the others.
  • I would rather use an extension method.
  • Thank you for this answer. I needed to skip over 3.3 billion rows and I could approximate the total number of bytes so this really saved me a lot of time.