我想在40-50個長文件中找到特定的字符串。要做到這一點,我用下面的代碼: -迭代StreamReader列表時出現空引用異常
foreach(StreamReader SR in FileList)
{
// Process the file
}
// File List contains initialized instances of StreamReader class
,而這樣做我收到
null reference exception
雖然,當
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
正如一些人指出,錯誤可能是由可變內容引起的,我想澄清一下,情況並非如此。
你必須添加更多的代碼(聲明/文件清單的人口,你是什麼在foreach裏面做,等)來幫助我們理解正在發生的事情。 – varocarbas
我已經添加了詳細信息。 –
'StreamReader'實現'IDisposable',你應該在'using'塊中初始化它 – DGibbs