How to fix NullReferenceException when reading a file in C#?

Yash Bokade 0 Reputation points
2026-11-19T16:01:18.4533333+00:00

I am trying to read lines from a text file using StreamReader in a C# console application, and I am encountering a System.NullReferenceException.

Here is the code I am using:

using (StreamReader reader = new StreamReader("data.txt"))

{

string line;

while ((line = reader.ReadLine()) != null)

{

    Console.WriteLine(line.ToUpper());

}

}

How can I safely check for null values or handle empty lines to avoid this exception?

Developer technologies | C#
Developer technologies | C#

An object-oriented and type-safe programming language that has its roots in the C family of languages and includes support for component-oriented programming.


2 answers

Sort by: Oldest
  1. AI answer

    2026-11-19T16:01:38.1533333+00:00

    StreamReader.ReadLine() returns null only when there are no more lines to read. In the loop shown, line is already checked before ToUpper() runs, so that pattern is safe for end-of-file.

    A NullReferenceException happens when code dereferences a null object reference. To avoid that, check values before calling members on them.

    Use one of these safe patterns:

    using System.IO;
    
    using (StreamReader reader = new StreamReader("data.txt"))
    {
        string? line;
        while ((line = reader.ReadLine()) != null)
        {
            Console.WriteLine(line.ToUpper());
        }
    }
    

    If the goal is to skip empty lines as well:

    using System.IO;
    
    using (StreamReader reader = new StreamReader("data.txt"))
    {
        string? line;
        while ((line = reader.ReadLine()) != null)
        {
            if (line.Length == 0)
                continue;
    
            Console.WriteLine(line.ToUpper());
        }
    }
    

    If the code should handle both null and empty strings explicitly:

    using System.IO;
    
    using (StreamReader reader = new StreamReader("data.txt"))
    {
        string? line;
        while ((line = reader.ReadLine()) != null)
        {
            if (string.IsNullOrEmpty(line))
                continue;
    
            Console.WriteLine(line.ToUpper());
        }
    }
    

    If a method can return null, test the return value before accessing its members. That is the recommended way to prevent NullReferenceException.

    A try/catch can be added for file I/O errors, but it is usually better to prevent NullReferenceException with null checks instead of handling it after it occurs:

    using System;
    using System.IO;
    
    try
    {
        using (StreamReader reader = new StreamReader("data.txt"))
        {
            string? line;
            while ((line = reader.ReadLine()) != null)
            {
                if (string.IsNullOrEmpty(line))
                    continue;
    
                Console.WriteLine(line.ToUpper());
            }
        }
    }
    catch (IOException e)
    {
        Console.WriteLine(e.Message);
    }
    

    Also note:

    • using ensures the StreamReader is disposed even if an exception is thrown.
    • Empty lines are not null; they are empty strings.
    • NullReferenceException is thrown when attempting to access a member on a null reference.

    AI-generated content may be incorrect. Read our transparency notes for more information.

    Was this answer helpful?

  2. Nguyen Dam (WICLOUD CORPORATION) 1,740 Reputation points Microsoft External Staff Moderator
    2026-11-20T02:26:15.1366667+00:00

    Hello @Yash Bokade and thank you for reaching out. 

    The code you've shared already checks for null before calling ToUpper(), so it should not cause a NullReferenceException under normal circumstances. 

    A few points worth noting: 

    • ReadLine() returns null at the end of the file, while empty lines are returned as "". Calling ToUpper() on an empty string is safe. 
    • You can use string.IsNullOrWhiteSpace(line) if you also want to skip lines containing only spaces or tabs. 
    • Issues such as a missing file or insufficient access permissions generally produce different exceptions rather than NullReferenceException. 

    If you're still encountering the exception, could you confirm which line throws it and share the exception's stack trace? 

    It may also be worth checking whether the code currently being executed matches the snippet you've posted, since the null check shown here should already prevent this particular issue. 

    If you found my response helpful or informative, I would greatly appreciate it if you could follow this guide for your confirmation. Thank you. 

    Was this answer helpful?

    0 comments No comments

Your answer

Answers can be marked as 'Accepted' by the question author and 'Recommended' by moderators, which helps users know the answer solved the author's problem.