Searches for a file with the specified name. The name of the file to find. The full path to the directory where the file can be found, or an empty string if the file does not exist in the locations searched. This method looks first in the directory of the currently executing assembly. If the specified file is not ther
(string fileName)
| 121 | /// each directory on the PATH environment variable, in order. |
| 122 | /// </remarks> |
| 123 | public static string FindFile(string fileName) |
| 124 | { |
| 125 | // Look first in the same directory as the executing assembly |
| 126 | string currentDirectory = GetCurrentDirectory(); |
| 127 | if (File.Exists(Path.Combine(currentDirectory, fileName))) |
| 128 | { |
| 129 | return currentDirectory; |
| 130 | } |
| 131 | |
| 132 | // If it's not in the same directory as the executing assembly, |
| 133 | // try looking in the system path. |
| 134 | string? systemPath = Environment.GetEnvironmentVariable("PATH"); |
| 135 | if (!string.IsNullOrEmpty(systemPath)) |
| 136 | { |
| 137 | string expandedPath = Environment.ExpandEnvironmentVariables(systemPath); |
| 138 | string[] directories = expandedPath.Split(Path.PathSeparator); |
| 139 | foreach (string directory in directories) |
| 140 | { |
| 141 | // N.B., if the directory in the path contains an invalid character, |
| 142 | // we will skip that directory, meaning no error will be thrown. This |
| 143 | // may be confusing to the user, so we might want to revisit this. |
| 144 | if (directory.IndexOfAny(Path.GetInvalidPathChars()) < 0) |
| 145 | { |
| 146 | if (File.Exists(Path.Combine(directory, fileName))) |
| 147 | { |
| 148 | currentDirectory = directory; |
| 149 | return currentDirectory; |
| 150 | } |
| 151 | } |
| 152 | } |
| 153 | } |
| 154 | |
| 155 | // Note that if it wasn't found on the system path, currentDirectory is still |
| 156 | // set to the same directory as the executing assembly. |
| 157 | return string.Empty; |
| 158 | } |
| 159 | |
| 160 | /// <summary> |
| 161 | /// Gets the directory of the currently executing assembly. |