Search code examples
c#filepath

Find a file by file name


What is the best way to find a file by its file name and then return its path?

e.g.

public string GetFilePath(string filename)
{
    // some work to get the path
    return filepath;
}

I have tried this but unsuccessfully

public string GetFileContent(string filename)
{
    DirectoryInfo hdDirectoryInWhichToSearch = new DirectoryInfo(@"c:\");
    FileInfo[] filesInDir = hdDirectoryInWhichToSearch.GetFiles("*" + filename + "*.*");

    foreach (FileInfo foundFile in filesInDir)
    {
        string fullName = foundFile.FullName;
        return fullName;
    }
    return "found nothing";
}

Is there a best practice approach for finding a file by its file name on the hard drive?


Solution

  • Try this:

    Directory.GetFiles(@"c:\", filename, SearchOption.AllDirectories).FirstOrDefault()