我想在 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 引起的,我想澄清事实并非如此。