Phương pháp sau tìm kiếm một tệp bắt đầu bằng đường dẫn khởi động ứng dụng (thư mục * .exe). Nếu không tìm thấy tệp ở đó, các thư mục mẹ sẽ được tìm kiếm cho đến khi tìm thấy tệp hoặc đến được thư mục gốc. nullđược trả lại nếu tệp không được tìm thấy.
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;
}
Lưu ý: Application.StartupPaththường được sử dụng trong các ứng dụng WinForms, nhưng nó cũng hoạt động trong các ứng dụng console; tuy nhiên, bạn sẽ phải thiết lập một tham chiếu đến System.Windows.Formsassembly. Bạn có thể thay thế Application.StartupPathbằng
Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location)nếu bạn thích.