Home > Software engineering >  c# - Finding the full path of a file on the hard disk
c# - Finding the full path of a file on the hard disk

Time:10-31

I want to get the full path of the file named wampmanager.conf on disk D. I coded the following for this:

private static string Scan(string path, string file)
{
    try
    {
        foreach (var dir in Directory.EnumerateDirectories(path))
        {
            foreach (var fl in Directory.EnumerateFiles(dir, file))
            {
                if (!string.IsNullOrEmpty(fl))
                {
                    return fl;
                }
            }
        }
    }
    catch (Exception)
    {
        // ignored
    }
    return null;
}

var wmc = Scan(@"D:\", "wampmanager.conf");
MessageBox.Show(wmc);

It always returns null even though the wampmanager.conf file exists on the disk D. I guess it goes to a directory like d:\recovery\ that I don't have access to, then it crashes into a catch and returns null. But when I don't use try catch I always get access authorization error. How can I deal with this problem?

CodePudding user response:

For each directory you must use SearchOption.AllDirectories to Includes the current directory and all its subdirectories in a search operation. Try this function:

    private static string Scan(string path, string file)
    {
        foreach (var dir in Directory.EnumerateDirectories(path))
        try
        {
            string[] files = Directory.GetFiles(dir, file, SearchOption.AllDirectories);
             if (files.Length > 0)
             {
                 return files[0];
             }
         }
         catch (Exception e)
         {
             string s = e.Message;
         }
        return "not found!";
    }
  • Related