2013-03-06 21 views
1

我想讓我的程序讀取文件夾中包含的所有文件,然後執行所需的操作。如何使用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(); 

回答

3

從你的描述中我不清楚你試圖達到什麼。但是,如果我理解正確的是它的要點,你可以收集所有文件中的所有行做任何處理之前:

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; 
+0

它工作。謝謝。 – 2013-03-06 13:10:13

1

要獲得所有文件的路徑中的一個文件夾,使用:

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

此外,您可以使用filePaths在所有這些文件上進行一些操作。

+0

這是行不通的。 – 2013-03-06 12:52:12

+0

@DorgySharma - 「這不行」 - 也許你用更多的話來解釋它? ) – MikroDel 2013-03-06 12:58:05

+0

如果你看到我的代碼,你會知道我在做什麼。首先,我想要讀取所有文件,然後僅執行任何操作。 – 2013-03-06 12:59:56

相關問題