How to navigate a few folders up?

前端 未结 11 2295
感动是毒
感动是毒 2020-11-29 20:52

One option would be to do System.IO.Directory.GetParent() a few times. Is there a more graceful way of travelling a few folders up from where the executing assembly resides?

11条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2020-11-29 21:22

    The following method searches a file beginning with the application startup path (*.exe folder). If the file is not found there, the parent folders are searched until either the file is found or the root folder has been reached. null is returned if the file was 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 is usually used in WinForms applications, but it works in console applications as well; however, you will have to set a reference to the System.Windows.Forms assembly. You can replace Application.StartupPath by
    Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location) if you prefer.

提交回复
热议问题