2013-11-01 41 views
0

我想在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 

正如一些人指出,錯誤可能是由可變內容引起的,我想澄清一下,情況並非如此。

+1

你必須添加更多的代碼(聲明/文件清單的人口,你是什麼在foreach裏面做,等)來幫助我們理解正在發生的事情。 – varocarbas

+0

我已經添加了詳細信息。 –

+1

'StreamReader'實現'IDisposable',你應該在'using'塊中初始化它 – DGibbs

回答

1

由於FileList爲空並且不包含任何元素,當然這會拋出異常。 在調用foreach之前,您應該檢查它是否爲空。 ..或者只是初始化FileList和新的之前來填充它。

+0

情況並非如此,我已檢查過它不爲空,請參閱對問題的編輯。 –

+0

你試過檢查它是否爲空?因爲在這一行foreach(FileList中的StreamReader SR)異常只能在FileList ==爲null時拋出 – decho

+0

FileList不爲null,而且如果我單獨打開這些文件,它就會打開。 –

1

檢查您的Content變量爲空,因爲如果SR爲空且未讀取,則可能SR.EndOfStream未正確設置。

如果有可能,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"); 
     } 
    } 
} 
1

StreamReader

從輸入流中的下一行,或空的文檔如果已到達輸入流的結束。

所以你正在閱讀傳遞流內容設置爲空的結束。

你應該爲此改變你的循環邏輯

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 

這會給你一個包含名稱

字符串的所有行
+0

錯誤不是由內容引起的。 –

+0

異常是由於SR爲空或內容爲空導致的,並且您聲明兩者都不爲空,但這些是代碼中的唯一對象,因此您與自己相矛盾 –

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; 
     } 
    } 
} 
相關問題