我正在使用此foreach循環搜索目錄中的文件,然後閱讀它們。看看文件是否包含特定的字符串,然後讀取該行
foreach (string file in Directory.EnumerateFiles(location, "*.MAI"))
在這個循環內,我想搜索文件中包含單詞「Sended」的行。有沒有辦法查找這個詞,然後閱讀該行?
我正在使用此foreach循環搜索目錄中的文件,然後閱讀它們。看看文件是否包含特定的字符串,然後讀取該行
foreach (string file in Directory.EnumerateFiles(location, "*.MAI"))
在這個循環內,我想搜索文件中包含單詞「Sended」的行。有沒有辦法查找這個詞,然後閱讀該行?
試試:
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
};
特別是對於非常大的文件,使用'ReadLines()' –
@HenkHolterman感謝您的評論,我同意你的意見,所以將此信息添加到答案中。 –
如果.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
}
}
}
我不知道'。 MAI',是那些文本文件?如果是這樣,ASCII,UTF-8?他們有多大(平均/最多)? –