Get a list of file names in a folder and in all subfolders

I need to get a list of all Word documents. * .doc and * .docx, which are stored in a folder under Windows, with many subfolders and sub-folders, etc.

Finding a file with C # has an answer that works, it is 2 years old and takes 10 seconds to search 1,500 files (in the future 10,000 or more). I will post my code, which is basically a copy from the link above. Does anyone have a better solution?

DateTime dt = DateTime.Now;
DirectoryInfo dir = new DirectoryInfo(MainFolder);
List<FileInfo> matches = 
          new List<FileInfo>(dir.GetFiles("*.doc*",SearchOption.AllDirectories));
TimeSpan ts = DateTime.Now-dt;
MessageBox.Show(matches.Count + " matches in " + ts.TotalSeconds + " seconds");
+2
source share
4 answers

Directory.EnumerateFiles GetFiles. , IEnumerable<T>, ( , , ).

, . , , / , - , .

:

EnumerateFiles GetFiles : EnumerateFiles, ; GetFiles, , . , , EnumerateFiles .

+5

, ,

dir.GetFiles("*.doc|*.docx", SearchOptions.AllDirectories) .

+2

, , Windows , . , # . , , FileSystemWatcher, , .

+1

For the first time, I suggest you use StopWatch instead of DateTime to get the elapsed time.
The second time, to speed up the search, you do not have to save the result of GetFiles in a list, but directly in an array.
And finally, you have to optimize your search pattern: you need every doc and docx file, try "* .doc?"
Here is my suggestion:

var sw = new Stopwatch();
sw.Start();

var matches = Directory.GetFiles(MainFolder, "*.doc?", SearchOption.AllDirectories);

sw.Stop();
MessageBox.Show(matches.Length + " matches in " + sw.Elapsed.TotalSeconds + " seconds");
+1
source

All Articles