Click here to Skip to main content
15,867,488 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
How can i find a all existing filePath by a fileName as an argument?
Suppose i have a file with name 
"test.txt"
Exist in
a)C:\
b)C:\TestFolder
c)D:\Main\Test
d)E:\


How can i enumerate through all the directories and sub-directories to get all the existing filePaths like
a)C:\test.txt
b)C:\TestFolder\test.txt
c)D:\Main\Test\test.txt
d)E:\test.txt


What I have tried:

var strFilePaths = new List<string>();
 foreach (var drive in DriveInfo.GetDrives())
 {
   String result = Directory.EnumerateFiles(drive , fileName,
                                      SearchOption.AllDirectories).First();

  strFilePaths.Add(result);
}
Posted
Updated 15-Dec-20 8:48am
Comments
PIEBALDconsult 15-Dec-20 15:52pm    
DIR /S/B C:\test.txt
DIR /S/B D:\test.txt
DIR /S/B E:\test.txt
etc.
PIEBALDconsult 15-Dec-20 15:53pm    
Unsure what you'll do about junctions and such though.

Enumerating Directories and Files on a Drive is a problem: as you may have found out, even a simple call to GetDirectories on your root drive may crash with one of several exceptions: UnauthorizedAccessException, PathTooLongException, IOException.

.NET 5 (Core) adds a new EnumerationOptions facility that will skip over errors: IgnoreInaccessible [^].

One solution for pre 5 .NET is to use the class published on StackOverflow in 2015 by Matthew Brubaker, and, then maintained, updated, on GitHub by Brian Hart: [^].

I am not using 5.0.
 
Share this answer
 
v2
Pretty much, you can't - you are going to have recurse the directories yourself, because unless your app has admin privileges, there are quite a few folders which you can;t access, and which will cause the Directory.EnumerateFiles Method (System.IO) | Microsoft Docs[^] to throw an UnauthorizedAccessException instead of processing files. This will certainly happen with drive C:, but on some systems it may also occur on other drives.

That means you will need to fetch each folder in turn, check it if you can (and skip it if you can't) then process all it's subfolders manually - you can't use AllDirectories if there are any restricted folders in the starting path! Almost certainly, this means a recursive method with try...catch block.
 
Share this answer
 
Comments
BillWoodruff 15-Dec-20 14:54pm    
Well, you can, but, it takes some hacking. And, .NET 5 will make it "easy" (insert snicker) ... if it is ever usable. See below.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900