Dorgy Sharma
Dorgy Sharma

Reputation: 55

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

I want my program to read all the files contained in a folder and then perform the desired operation.

I have tried the following code, but this is giving me results by reading one file and then displaying result i.e. file by file:

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();

Upvotes: 1

Views: 270

Answers (2)

Rune
Rune

Reputation: 8380

It is not crystal clear to me from your description what it is you are trying to achieve. However, if I understand the gist of it correctly, you could collect all lines of all files before doing any processing:

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

or, using integrated language features

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

Upvotes: 3

MikroDel
MikroDel

Reputation: 6735

To get path of all files in a folder, use:

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

Further you can work with filePaths to take some actions you need on all this files.

Upvotes: 1

Related Questions