Penguen
Penguen

Reputation: 17298

how to find file's path according to filename?

i have filename according to this file name. i need to find file's path. how to find file's path according to filename? i need to find file's path according to file name sample code:

string path=      System.IO.Directory.GetDirectories(@"c:\", "kategori",System.IO.SearchOption.AllDirectories).First();

But i need :

string path=      System.IO.Directory.GetDirectories(@"anyFolder", "kategori",System.IO.SearchOption.AllDirectories).First();

i need below


Main()
{
string path = PathFinder("Afilename")
}

output: C:\myFiles\AfileName

string PathFinder(string fileName)
{
..................
.................
........
.......
....
..
.
}

Upvotes: 0

Views: 1312

Answers (3)

Oliver
Oliver

Reputation: 45119

I'd like more the LINQish way:

public static IEnumerable<FileInfo> FindFile(string fileName)
{
    if (String.IsNullOrEmpty(fileName))
        throw new ArgumentException("fileName");

    return Directory.GetLogicalDrives()
                    .SelectMany(drive => FindFile(fileName, drive));
}

public static IEnumerable<FileInfo> FindFile(string fileName, string folderName)
{
    if (String.IsNullOrEmpty(fileName))
        throw new ArgumentException("fileName");
    if (String.IsNullOrEmpty(fileName))
        throw new ArgumentException("folderName");

    var matchingFiles = Directory.EnumerateFiles(folderName)
                                 .Where(file => Path.GetFileName(file) == fileName)
                                 .Select(file => new FileInfo(file));

    var matchingFilesFromSubDirs = Directory.EnumerateDirectories(folderName)
                                            .SelectMany(directory => FindFile(fileName, directory));

    return matchingFiles.Concat(matchingFilesFromSubDirs);
}

which can be used by:

foreach (var file in FindFile("myFile.ext"))
{
    Console.WriteLine("Name: " + file.FullName);
}

Upvotes: 2

Erik Burigo
Erik Burigo

Reputation: 317

Probably a function like this could work for you:

public static String SearchFileRecursive(String baseFolderPath, String fileName)
    {
        // Returns, if found, the full path of the file; otherwise returns null.
        var response = Path.Combine(baseFolderPath, fileName);
        if (File.Exists(response))
        {
            return response;
        }

        // Recursion.
        var directories = Directory.GetDirectories(baseFolderPath);
        for (var i = 0; i < directories.Length; i++)
        {
            response = SearchFileRecursive(directories[i], fileName);
            if (response != null) return response;
        }

        // { file was not found }

        return null;
    }

Upvotes: 3

Related Questions