Null reference exception while iterating over a list of StreamReader objects

守給你的承諾、 提交于 2019-12-11 20:29:29

问题


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?


回答1:


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);
}


来源:https://stackoverflow.com/questions/19610525/null-reference-exception-while-iterating-over-a-list-of-streamreader-objects

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!