[英]How to read all lines from notepad comma separated and updated specific column conditionally in C#
[英](C#) How to read all files in a folder to find specific lines?
我是C#的新手,所以請多加耐心。 我想要做的是讀取文件夾中的所有文件,以找到特定的行(在同一文件中可能會出現多次),並將輸出顯示在屏幕上。
如果有人能指出我需要使用的方法的方向,那將是很好的。 謝謝!
從...開始
const string lineToFind = "blah-blah";
var fileNames = Directory.GetFiles(@"C:\path\here");
foreach (var fileName in fileNames)
{
int line = 1;
using (var reader = new StreamReader(fileName))
{
// read file line by line
string lineRead;
while ((lineRead = reader.ReadLine()) != null)
{
if (lineRead == lineToFind)
{
Console.WriteLine("File {0}, line: {1}", fileName, line);
}
line++;
}
}
}
正如尼克在下面指出的那樣,您可以使用任務庫進行並行搜索,只需將'foreach'替換為Parallel.Foreach(filesNames,file => {..});即可。
Directory.GetFiles: http : //msdn.microsoft.com/en-us/library/07wt70x2
StreamReader: http : //msdn.microsoft.com/en-us/library/f2ke0fzy.aspx
您想在屏幕上獲得什么輸出 ?
如果要查找具有給定行的第一個文件,可以使用以下短代碼:
var firstMatchFilePath = Directory.GetFiles(@"C:\Temp", "*.txt")
.FirstOrDefault(fn => File.ReadLines(fn)
.Any(l => l == lineToFind));
if (firstMatchFilePath != null)
MessageBox.Show(firstMatchFilePath);
我已將Directory.GetFiles
與搜索模式一起使用來查找目錄中的所有文本文件。 我已經使用LINQ擴展方法FirstOrDefault
和Any
查找具有給定行的第一個文件。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.