0

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

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

4

1 回答 1

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

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

using (StreamReader sr = new StreamReader("filename.txt"))
{
    Files.Add("filename.txt", sr);
}
于 2013-10-26T18:53:54.967 回答