Ojen
Ojen

Reputation: 13

How to load large file with StreamReader in C#?

I'm using StreamReader in C# to load a txt file into a list it's work fine with small size file <= 20 Mb but when I need to load large files the prepossess stopped and show me this

Your app has entered a break state, but no code is currently executing that is supported by the selected debug engine (e.g. only native runtime code is executing).

I'm using Visual Studio 2017.

This is the code

line = reader.ReadLine();

while (line != null)
{
    if (line.Contains("@"))
    {
        myEmails.Add(line);
        line = reader.ReadLine();
    }
}
reader.Close();

Upvotes: 1

Views: 89

Answers (1)

Martin
Martin

Reputation: 16433

Your code just has a minor logical error.

In your loop, you are looking for lines containing an @ symbol. If the line has one, it adds it to myEmails and gets the next line.

However, if the line does not contain an @, the next line is never read so you enter an infinite loop.

You just need to move line = reader.ReadLine(); outside of your if statement and it will always read the next line regardless of whether it contains an @ symbol:

line = reader.ReadLine();
while (line != null)
{
    if (line.Contains("@"))
        myEmails.Add(line);

    line = reader.ReadLine();
}
reader.Close();

Upvotes: 3

Related Questions