Search code examples
c#.netfile-ionullreferenceexceptionstreamreader

Null reference exception while iterating over a list of StreamReader objects


I am making a simple Program which searches for a particular Name in a set of files.I have around 23 files to go through. To achieve this I am using StreamReader class, therefore, to write less of code, I have made a

List<StreamReader> FileList = new List<StreamReader>();

list containing elements of type StreamReader and my plan is to iterate over the list and open each file:

foreach(StreamReader Element in FileList)
{
    while (!Element.EndOfStream)
    {
        // Code to process the file here.
    }
}

I have opened all of the streams in the FileList.The problem is that I am getting a

Null Reference Exception

at the condition in the while loop.

Can anybody tell me what mistake I am doing here and why I am getting this exception and what are the steps I can take to correct this problem?


Solution

  • As peoples described on above, Use the following way:

    using (StreamReader sr = new StreamReader("filename.txt"))
    {
        ...
    }
    

    If you're trying to store files with their names on a list, I suggest you to use a dictionary:

    Dictionary<string, string> Files = new Dictionary<string, string>();
    
    using (StreamReader sr = new StreamReader("filename.txt"))
    {
       string total = "";
       string line;
       while ((line = sr.ReadLine()) != null)
       {
          total += line;
       }
       Files.Add("filename.txt", line);
    }
    

    To access them:

    Console.WriteLine("Filename.txt has: " + Files["filename.txt"]);
    

    Or If you want to get the StreamReader It self not the file text, You can use:

    Dictionary<string, StreamReader> Files = new Dictionary<string, StreamReader>();
    
    using (StreamReader sr = new StreamReader("filename.txt"))
    {
        Files.Add("filename.txt", sr);
    }