Skip to main content
 首页 » 编程设计

c#之如何使用 C# 读取文件夹中存在的一个实例中的所有文件

2024年02月20日11JeffreyZhao

我希望我的程序读取文件夹中包含的所有文件,然后执行所需的操作。

我已经尝试了以下代码,但这是通过读取一个文件然后显示结果(即逐个文件)来给我结果的:

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;