1

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.

2
  • 2
    If file.ReadLine() doesn't return anything, you'll get a NullReferenceException (the one you're getting) when you call Trim() Commented Jun 27, 2018 at 17:17
  • Two things: 1. Try to make an effort to format your code. People will be more willing to help if they can read your code. 2. Make sure the code you do provide can compile. You have a number of mistakes in the code that won't compile. For example: using sting instead of string. console.write should be capitalized: Console.Write Commented Jun 27, 2018 at 21:45

2 Answers 2

2

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.

Sign up to request clarification or add additional context in comments.

Comments

1

Use the ?. operator, like:

file.ReadLine()?.Trim()

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.