【问题标题】:Null reference exception while iterating over a list of StreamReader objects遍历 StreamReader 对象列表时出现空引用异常
【发布时间】:2013-10-26 18:46:03
【问题描述】:

我正在制作一个简单的程序,它在一组文件中搜索特定名称。我有大约 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 循环中的条件。

谁能告诉我我在这里犯了什么错误,为什么会出现这个异常以及我可以采取哪些步骤来纠正这个问题?

【问题讨论】:

  • using 块内扭曲你的代码,它会破坏任何未清理的对象。
  • 那么FileList 中有空引用吗? 究竟堆栈跟踪是什么样的?
  • @Khushi 你能详细解释一下,因为我是 C# 新手
  • @Khushi:using 语句将确保调用 Dispose。它实际上不会破坏对象。
  • @JonSkeet 我错了。感谢您提及。

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


【解决方案1】:

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

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 Itself 而不是文件文本,你可以使用:

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

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

【讨论】:

  • 感谢您的回答,您能告诉我为什么会收到空引用异常吗?
  • @Patrik 这完全取决于您的 StreamReaders 代码部分,您可能已经关闭了 StreamReaders,保持 StreamReader(文件)打开并不是一个好主意,因为它会使其处于使用状态并且不允许任何其他应用程序使用它,最好的方法是从它收集你想要的(字符串)然后关闭,将字符串保存到内存中。你不应该让它们永远打开。确保 Dispose();被称为最好的方法是使用 using 格式。对 StreamWriters 也采取同样的方法。
  • 感谢您的建议。由于文件很多,我又制作了两个函数来跟踪流的打开和关闭,所以只要调用这个函数,我就会调用 close 函数,所以没有流是打开的
  • 在声明sr 的情况下,您不能将其放入using 块中,因为这会使StreamReader 无用。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-02-12
  • 1970-01-01
相关资源
最近更新 更多