0

我想在 40-50 个长文件中找到一个特定的字符串。为此,我使用了以下代码:-

    foreach(StreamReader SR in FileList)
    {
       // Process the file
    }
    // File List contains initialized instances of StreamReader class

在这样做的同时我收到

       null reference exception

虽然,当

    FileList 

仅包含 1 个元素,代码工作正常。这可能是什么原因,如何纠正?我做了一个这样的函数,它初始化文件并将它们添加到 FileList:

    public static void Initialize()
    {
      StreamReader File1 = new StreamReader("some valid path here",false, Encoding.UTF8) ; 
       FileList.Add(File1) ; 
       // Similarly for other files.
    } 

foreach 循环内的代码是:-

    foreach( StreamReader SR in FileList)
    {
      while (!SR.EndOfStream)
      {
          Content = SR.ReadLine() ; 
          if(Content.Contains(Name))
          {
           Console.WriteLine("Found");
          }
       }
     } 
      // Content and Name are other string variable declared previously in the program

正如一些人指出的那样,错误可能是由变量 Content 引起的,我想澄清事实并非如此。

4

4 回答 4

1

检查您的Content变量是否为空,因为如果为空且未读取,SR.EndOfStream则可能未正确设置。SR

如果可能,在 中有空条目FileList,也检查SR空。

foreach( StreamReader SR in FileList)
{
  if(SR == null) continue;

  while (!SR.EndOfStream)
  {
      Content = SR.ReadLine() ; 
      if(Content != null && Content.Contains(Name))
      {
       Console.WriteLine("Found");
      }
   }
 } 
于 2013-11-01T09:57:34.350 回答
1

可能是因为 FileList 为 null 并且不包含任何元素。当然这会抛出异常。在调用 foreach 之前,您应该检查 this 是否为空。..或者只是在某个地方用新的FileList初始化来填充它。

于 2013-11-01T09:42:57.370 回答
1

从文档StreamReader

输入流的下一行,如果到达输入流的末尾,则返回 null。

因此,您正在阅读将 Content 设置为 null 的流的末尾。

你应该因此改变你的循环逻辑

    while ((Content = SR.ReadLine()) != null)
    {
        if (Content.Contains(Name))
        {
            Console.WriteLine("Found");
        }
    }

但是我建议做的完全不同

var paths = //set to a list of file paths
var findings = from path in paths
               from line in System.IO.File.ReadAllLines(path)
               where line.Contains(name)
               select line

这将为您提供包含名称中的字符串的所有行

于 2013-11-01T10:06:17.580 回答
1

有一个非常好的和安全的方法File.ReadLines(不要与 File.ReadAllLines 混淆)

它不会读取文件的全部内容,但会在每次调用时加载一行

foreach (string path in paths)
{
    foreach (string line in File.ReadLines(path))
    {
        if (line.Contains(Name))
        {
            Console.WriteLine("found");
            break;
        }
    }
}
于 2013-11-01T10:07:28.873 回答