A solution using 'EnumerateFiles, which may be faster than using 'GetFiles:
private bool findFilePath(string directoryPath, string fileName, out string result)
{
string fullPath = Path.Combine(directoryPath, fileName);
if (File.Exists(fullPath))
{
result = fullPath;
return true;
}
result = string.Empty;
try
{
result = Directory.EnumerateFiles(directoryPath, fileName, SearchOption.AllDirectories).First();
}
catch
{
return false;
}
return true;
Example of calling this method:
string result;
if (findFilePath(@"C:\Program Files", @"CASdb.accdb", out result))
{
}
Discussion:
First, note that there are some Directories in the boot-drive 'Program Files folder, like 'WindowsApps, that you cannot access with either 'GetFiles or 'EnumerateFiles unless you have the access right of "TrustedInstaller." For example with Win 8 see:[
^]. Trying to access directories with TrustedInstaller status will result in an application breaking error.
For how to create "TrustedInstaller" access (manually) in the FileExplorer: [
^].
Getting this kind of permission in C# code is complex: start here to get oriented: [
^], and then see: [
^], [
^].
Modifying TrustedInstaller status directory access
is probably something you should not be doing for security reasons ... unless you are a legitimate SysAdmin. Get ready for some serious study if you need to take this on !