user5593927
user5593927

Reputation: 15

C# code to search exact file name in Windows folder

I have a set of files present somewhere in my Windows folder. I only know their root path and not their exact path. See below:

List of files:

  1. Linq.doc

  2. OOPs.doc

Root path is:

  1. E:\RootFolder......\Linq.doc

  2. E:\RootFolder......\OOPs.doc

I need to fetch their full path from my .Net code. So the output returned should be something like this:

Output required:

  1. E:\RootFolder\SubFolder1\Linq.doc

  2. E:\RootFolder\SubFolder1\SubFolder9\OOPs.doc

I tried using following code, but it is returning incorrect results:

Directory.SetCurrentDirectory(@"E:\RootFolder");
var Filepath= Directory.GetDirectories("Linq.doc","*.doc*",SearchOption.AllDirectories);

Please advise what can be a better solution?

Upvotes: 1

Views: 1258

Answers (2)

user5593927
user5593927

Reputation: 15

I figured out the solution which is to use EnumerateFiles with a "Where" clause. See the code below:

var results2 = Directory.EnumerateFiles(@"E:\RootFolder", "*.doc", SearchOption.AllDirectories).Where(p => p.Contains(sFile2)); 

Using EnumerateFiles is more efficient than using GetFiles. This resolves my question.

Upvotes: 1

Philipp Grathwohl
Philipp Grathwohl

Reputation: 2846

You can use Directory.GetFiles instead of Directory.GetDirectories

System.IO.Directory.GetFiles(@"E:\RootFolder", "Linq.doc", SearchOption.AllDirectories);

See documentation here

Upvotes: 3

Related Questions