Finding a file using C #

What would be a quick way to search for a file programmatically in C #. I know the relative location of the file, let's say it. "abcd\efgh\test.txt".I also know that this file is on mine E:\ drive. "abcd" is a subdirectory in a directory in the E: \ directory.

thank

+2
source share
5 answers

Since you know the root directory you want to find and the string pattern for the file name, you can create DirectoryInfo with the root directory:

DirectoryInfo dir = new DirectoryInfo(@"E:\");

And then call GetFiles()to get all matches. Passing SearchOption.AllDirectoriesensures that the search is recursive.

List<FileInfo> matches = 
    new List<FileInfo>(dir.GetFiles(partialFilename, 
        SearchOption.AllDirectories));

Or, if you know part of the path (instead of the file name):

List<DirectoryInfo> matches =
    new List<DirectoryInfo>(dir.GetDirectories(partialDirectoryName,
        SearchOption.AllDirectories));

And then you can go to the file from there.

+2
source

, , , :

"E:\\" + something + "\\abcd\\efgh\\test.txt"

something 1 , E:, .

something 1 , , , abcd.

0

, , FindFirstFile .. api, , ( ) Directory.GetDirectories ( ), Directory.GetFiles .

0

File.Exists . , - ( ):

 string SearchInFolder(string root) {

    if (File.Exists(Path.Append(root, "\\abcd\\efgh\\test.txt")) return Path.Append(root, "\\abcd\\efgh\\test.txt");
    foreach(var folder in Directory.GetDirectories(root)) {
       var fullFile = Path.Append(folder, "\\abcd\\efgh\\test.txt");
       if (File.Exists(fullFile)) {
           // Found it !!!!
           return fullFile;
       } else {
           var result = SearchInFolder(folder);
           if (result != null) return result;
       }
    }
    return null;
 }

E:\ , .

0

I think the algorithm will start with e: \ and read all directories. If one of them is \ abcd \, immediately check the rest of the path and file, for example, efgh \ test.txt.

If e: \ does NOT have \ abcd \, you need to go to each subdirectory and perform the same check. Does \ abcd \ exist? Yes, check efgh \ text.txt. No? Underwater traverses.

If you need absolutely fast when you cannot find \ abcd \, and you have a list of subdirectors, you should now check, you can enter some level of streaming. But it can be quite hairy.

0
source

All Articles