The following method looks for a file starting with the application launch path (* .exe folder). If the file is not found there, the parent folders are executed until neither the file nor the root folder is found. null returned if the file is not found.
public static FileInfo FindApplicationFile(string fileName) { string startPath = Path.Combine(Application.StartupPath, fileName); FileInfo file = new FileInfo(startPath); while (!file.Exists) { if (file.Directory.Parent == null) { return null; } DirectoryInfo parentDir = file.Directory.Parent; file = new FileInfo(Path.Combine(parentDir.FullName, file.Name)); } return file; }
Note. Application.StartupPath commonly used in WinForms applications, but also works in console applications; however, you will need to install a link to the System.Windows.Forms assembly. You can replace Application.StartupPath with
Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location) , if you prefer.
Olivier Jacot-Descombes Feb 11 '14 at 18:26 2014-02-11 18:26
source share