How to navigate a few folders up?

前端 未结 11 2289
感动是毒
感动是毒 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:21
    public static string AppRootDirectory()
            {
                string _BaseDirectory = AppDomain.CurrentDomain.BaseDirectory;
                return Path.GetFullPath(Path.Combine(_BaseDirectory, @"..\..\"));
            }
    
    0 讨论(0)
  • 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.

    0 讨论(0)
  • 2020-11-29 21:28

    Other simple way is to do this:

    string path = @"C:\Folder1\Folder2\Folder3\Folder4";
    string newPath = Path.GetFullPath(Path.Combine(path, @"..\..\"));
    

    Note This goes two levels up. The result would be: newPath = @"C:\Folder1\Folder2\";

    0 讨论(0)
  • 2020-11-29 21:32

    If you know the folder you want to navigate to, find the index of it then substring.

                var ind = Directory.GetCurrentDirectory().ToString().IndexOf("Folderame");
    
                string productFolder = Directory.GetCurrentDirectory().ToString().Substring(0, ind);
    
    0 讨论(0)
  • 2020-11-29 21:34

    I have some virtual directories and I cannot use Directory methods. So, I made a simple split/join function for those interested. Not as safe though.

    var splitResult = filePath.Split(new[] {'/', '\\'}, StringSplitOptions.RemoveEmptyEntries);
    var newFilePath = Path.Combine(filePath.Take(splitResult.Length - 1).ToArray());
    

    So, if you want to move 4 up, you just need to change the 1 to 4 and add some checks to avoid exceptions.

    0 讨论(0)
提交回复
热议问题