How to read all text from all txt files (*. Txt)

I need to use the fastest method (in my opinion, this is readalltext), how to read alltext from txt files, I do not know how to fix the code:

string[] files = Directory
  .GetFiles(@"C:\Users\Wiz\Desktop\test","*.txt", SearchOption.AllDirectories);

var letter = File.ReadAllText(files);
+4
source share
3 answers

An interesting thing for me was to indicate what is the fastest way, and so I tried 3 methods:

Overview

overview * ~ 200 Ticks

Conclusion

Parallel approximation works best in this case, Directory.EnumerateFilesmuch faster than Directory.GetFiles(search using the * .txt template and subdirectories)

the code

A - GetFiles and ReadAllText

foreach (var file in Directory.GetFiles("C:\\Program Files (x86)", "*.txt", SearchOption.AllDirectories))
{
   var a = File.ReadAllText(file);
}

B - EnumerateFiles and ReadAllText

foreach (var file in Directory.EnumerateFiles("C:\\Program Files (x86)", "*.txt", SearchOption.AllDirectories))
{
   var a = File.ReadAllText(file);
}

C - Parallel Approach

var files = Directory.EnumerateFiles("C:\\Program Files (x86)", "*.txt", SearchOption.AllDirectories);
Parallel.ForEach(files,(current) => 
{
    var a = File.ReadAllText(current);
});

FEEL FREE to add ideas, thoughts, ....

+2
source

File.ReadAllText , Directory.GetFiles . loop/linq

string sDir = @"C:\Users\Wiz\Desktop\test";
string[] files = Directory.GetFiles(sDir, "*.txt", SearchOption.AllDirectories);
string[] letters = files.Select(x => File.ReadAllText(x)).ToArray();
+2

You need to use a loop to read all files, as ReadAllText will read one file at a time.

foreach (var file in files)
{
    // Do the reading of your file here.
}
+1
source

All Articles