2015-06-25 93 views
1

我正在使用此foreach循環搜索目錄中的文件,然後閱讀它們。看看文件是否包含特定的字符串,然後讀取該行

foreach (string file in Directory.EnumerateFiles(location, "*.MAI")) 

在這個循環內,我想搜索文件中包含單詞「Sended」的行。有沒有辦法查找這個詞,然後閱讀該行?

+1

我不知道'。 MAI',是那些文本文件?如果是這樣,ASCII,UTF-8?他們有多大(平均/最多)? –

回答

4

試試:

var location = @"<your location>"; 
foreach (string file in Directory.EnumerateFiles(location, "*.MAI")) 
{ 
    var findedLines = File.ReadAllLines(file) 
          .Where(l => l.Contains("Sended")); 
} 

如果你處理大文件,你應該使用readlines方法方法,因爲當你使用readlines方法,你就可以開始枚舉字符串前集合全收集回;當您使用ReadAllLines時,必須等待返回整個數組的字符串才能訪問該數組。

從MSDN又如:

var files = from file in Directory.EnumerateFiles(location, "*.MAI") 
      from line in File.ReadLines(file) 
      where line.Contains("Sended") 
      select new 
      { 
       File = file, 
       Line = line 
      }; 

的全部信息,請看這裏:https://msdn.microsoft.com/library/dd383503.aspx

+2

特別是對於非常大的文件,使用'ReadLines()' –

+0

@HenkHolterman感謝您的評論,我同意你的意見,所以將此信息添加到答案中。 –

1

如果.MAI文件TEXTFILES嘗試以下操作:

 foreach (string file in Directory.EnumerateFiles(location, "*.MAI")) 
     { 
      foreach (string Line in File.ReadAllLines(file)) 
      { 
       if (Line.Contains("Sended")) 
       { 
        //Do your stuff here 
       } 
      } 
     } 
相關問題