cs0815
cs0815

Reputation: 17418

code terminates prematurely whilst looping over large file

I am looping over each row of a large file suing this straight forward code:

using (var reader = new StreamReader(@"C:\SomeBigFile.txt"))
{
    while (reader.ReadLine() != null)
    {
        var line = reader.ReadLine();

        // some more stuff
    }
}

At about line 7000000 an empty line is found and after that reader.ReadLine() returns null. So the code terminates. However, when I expect the file in a text editor, there are definitely more rows after that and I cannot see an issue with the row which returns an empty line. Is there a way to make the above truly finish reading the file? Thanks!

Upvotes: 0

Views: 37

Answers (1)

Jeroen van Langen
Jeroen van Langen

Reputation: 22073

You're skipping a line in the while. Thats why you are losing data.

try this:

using (var reader = new StreamReader(@"C:\SomeBigFile.txt"))
{
    while (!reader.EndOfStream)
    {
        var line = reader.ReadLine();


    // some more stuff
    }
}

Mostly i'm using this:

var filename = @"C:\SomeBigFile.txt";

foreach(var line in File.ReadLines(filename))
{
    //  ....
}

It returns an IEnumerable<string> which read the file line by line.

Upvotes: 5

Related Questions