簡體   English   中英

如何使用C#讀取文件夾中存在的一個實例中的所有文件?

[英]How to read all the files in one instance present in a folder using C#?

我希望我的程序讀取文件夾中包含的所有文件,然后執行所需的操作。

我已經嘗試了以下代碼,但這是通過讀取一個文件然后顯示結果(即逐個文件)給我結果:

foreach (string file in Directory.EnumerateFiles(@"C:\Users\karansha\Desktop\Statistics\Transfer", "*.*", SearchOption.AllDirectories))
{
                Console.WriteLine(file);

                System.IO.StreamReader myFile = new System.IO.StreamReader(file);
                string searchKeyword = "WX Search";
                string[] textLines = File.ReadAllLines(file);
                Regex regex = new Regex(@"Elapsed Time:\s*(?<value>\d+\.?\d*)\s*ms");
                double totalTime = 0;
                int count = 0;
                foreach (string line in textLines)
                {
                    if (line.Contains(searchKeyword))
                    {
                        Match match = regex.Match(line);
                        if (match.Captures.Count > 0)
                        {
                            try
                            {
                                count++;
                                double time = Double.Parse(match.Groups["value"].Value);
                                totalTime += time;
                            }
                            catch (Exception)
                            {
                                // no number
                            }
                        }
                    }
                }
                double average = totalTime / count;
                Console.WriteLine("RuleAverage=" + average);
                // keep screen from going away
                // when run from VS.NET
                Console.ReadLine();

從你的描述中我不清楚你想要實現的是什么。 但是,如果我正確理解了它的要點,您可以在進行任何處理之前收集所有文件的所有行:

IEnumerable<string> allLinesInAllFiles
                              = Directory.GetFiles(dirPath, "*.*")
                                .Select(filePath => File.ReadLines(filePath))
                                .SelectMany(line => line);
//Now do your processing

或者,使用集成的語言功能

IEnumerable<string> allLinesInAllFiles = 
    from filepath in Directory.GetFiles(dirPath, "*.*")
    from line in File.ReadLines(filepath)
    select line;

要獲取文件夾中所有文件的路徑,請使用:

string[] filePaths = Directory.GetFiles(yourPathAsString);

此外,您可以使用filePaths對所有這些文件執行所需的操作。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM