迭代StreamReader对象列表时出现空引用异常

时间:2013-10-26 18:46:04

标签: c# .net file-io nullreferenceexception streamreader

我正在制作一个简单的程序,它在一组文件中搜索特定的名称。我有大约23个文件要经过。为了实现这一点,我使用StreamReader类,因此,编写更少的代码,我做了一个

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

包含StreamReader类型元素的列表和我的计划是迭代列表并打开每个文件:

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

我已经打开了FileList中的所有流。问题是我得到了一个

  

空引用异常

在while循环中的条件。

有人能告诉我我在这里做了什么错,为什么我得到这个例外,我可以采取哪些措施来纠正这个问题?

1 个答案:

答案 0 :(得分:2)

如上所述,请使用以下方式:

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

如果您尝试将名称中的文件存储在列表中,我建议您使用字典:

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

要访问它们:

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

或者如果你想获得StreamReader它不是文件文本,你可以使用:

Dictionary<string, StreamReader> Files = new Dictionary<string, StreamReader>();

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