codeZach
codeZach

Reputation: 39

Getting exception when reading two lines of data from text file in C#

Hello I am reading two line of data from text file in C#, and at the end of file I get error "Object reference not set to an instance of an object". I know this error is because of end of file, and object is being assigned null value. But i need to avoid this error. My code is in below format:

try
{
    sting line;
    while ((line = file.ReadLine().Trim()) != null)
    {
        //do something
        if ((line2 = file.ReadLine().Trim()) != null)
        //do something
    }
}
catch(exception e)
{
    console.write(e.Message);
}

At end of file, is where it goes in exception.

Thanks for help in advance.

Upvotes: 1

Views: 45

Answers (2)

TrueWill
TrueWill

Reputation: 25523

The issue is that the code is calling Trim() on the result of the ReadLine() before checking if the result is null.

From How to: Read a Text File One Line at a Time (Visual C#):

while((line = file.ReadLine()) != null)  
{
    // Do something with line
}

Also note that it's generally best to avoid calling ReadLine() again within the loop.

Upvotes: 2

user4610426
user4610426

Reputation:

Use the ?. operator, like:

file.ReadLine()?.Trim()

Upvotes: 1

Related Questions