How to navigate a few folders up?

前端 未结 11 2288
感动是毒
感动是毒 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:09

    You can use ..\path to go one level up, ..\..\path to go two levels up from path.

    You can use Path class too.

    C# Path class

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

    This is what worked best for me:

    string parentOfStartupPath = Path.GetFullPath(Path.Combine(Application.StartupPath, @"../"));

    Getting the 'right' path wasn't the problem, adding '../' obviously does that, but after that, the given string isn't usable, because it will just add the '../' at the end. Surrounding it with Path.GetFullPath() will give you the absolute path, making it usable.

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

    if c:\folder1\folder2\folder3\bin is the path then the following code will return the path base folder of bin folder

    //string directory=System.IO.Directory.GetParent(Environment.CurrentDirectory).ToString());
    
    string directory=System.IO.Directory.GetParent(Environment.CurrentDirectory).ToString();
    

    ie,c:\folder1\folder2\folder3

    if you want folder2 path then you can get the directory by

    string directory = System.IO.Directory.GetParent(System.IO.Directory.GetParent(Environment.CurrentDirectory).ToString()).ToString();
    

    then you will get path as c:\folder1\folder2\

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

    this may help

    string parentOfStartupPath = Path.GetFullPath(Path.Combine(Application.StartupPath, @"../../")) + "Orders.xml";
    if (File.Exists(parentOfStartupPath))
    {
        // file found
    }
    
    0 讨论(0)
  • 2020-11-29 21:20

    C#

    string upTwoDir = Path.GetFullPath(Path.Combine(System.AppContext.BaseDirectory, @"..\..\"));
    
    0 讨论(0)
  • 2020-11-29 21:21

    Maybe you could use a function if you want to declare the number of levels and put it into a function?

    private String GetParents(Int32 noOfLevels, String currentpath)
    {
         String path = "";
         for(int i=0; i< noOfLevels; i++)
         {
             path += @"..\";
         }
         path += currentpath;
         return path;
    }
    

    And you could call it like this:

    String path = this.GetParents(4, currentpath);
    
    0 讨论(0)
提交回复
热议问题