173

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?

What I am trying to do is find a text file that resides one folder above the application folder. But the assembly itself is inside the bin, which is a few folders deep in the application folder.

3
  • 2
    usually a relative path does the trick like '..\..\..\..\Downfolder' but it depends on what exactly you're trying to do this for...?
    – DiskJunky
    Feb 15, 2013 at 16:52
  • is this always the case?
    – CR41G14
    Feb 15, 2013 at 16:52
  • 4
    "Navigate" how? Do you mean the current directory? If so, you should be able to do Directory.SetCurrentDirectory(@"..\..\..\.."); Feb 15, 2013 at 16:53

13 Answers 13

305

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\";

Additional Note Path.GetFullPath normalizes the final result based on what environment your code is running on windows/mac/mobile/...

6
  • 55
    There is no point using Path.Combine when you are adding backslash manually anyway. Consider using Path.Combine(path, "..", "..") instead.
    – AXMIM
    Apr 6, 2019 at 19:12
  • 2
    @AXMIM using GetFullPath will return the absolute path, it makes a difference in most situation. Try entering the above code in CodeBunk and see the result would be different if not using GetFullPath, and in most cases might cause bugs. Oct 13, 2020 at 23:53
  • Will that work for any OS or only for some specific that use backslash in paths, e.g., Windows? Jun 23, 2021 at 9:27
  • @alcoholisevil I've tested in on Windows, not sure about Mac, I guess it should work on mac as well. (getFullPath should normalize path string for each environment/os) Jun 24, 2021 at 0:57
  • 2
    You can also combine them (and would be better probably): Path.GetFullPath(Path.Combine(path, "..", "..")) Mar 6, 2022 at 21:58
48

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\

14

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

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.

6
public static string AppRootDirectory()
        {
            string _BaseDirectory = AppDomain.CurrentDomain.BaseDirectory;
            return Path.GetFullPath(Path.Combine(_BaseDirectory, @"..\..\"));
        }
6

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.

I use this strategy to find configuration and resource files. This allows me to share them for multiple applications or for Debug and Release versions of an application by placing them in a common parent folder.

5

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
5

C#

string upTwoDir = Path.GetFullPath(Path.Combine(System.AppContext.BaseDirectory, @"..\..\"));
3

Hiding a looped call to Directory.GetParent(path) inside an static method is the way to go.

Messing around with ".." and Path.Combine will ultimately lead to bugs related to the operation system or simply fail due to mix up between relative paths and absolute paths.

public static class PathUtils
{
    public static string MoveUp(string path, int noOfLevels)
    {
        string parentPath = path.TrimEnd(new[] { '/', '\\' });
        for (int i=0; i< noOfLevels; i++)
        {
            parentPath = Directory.GetParent(parentPath ).ToString();
        }
        return parentPath;
    }
}
1

this may help

string parentOfStartupPath = Path.GetFullPath(Path.Combine(Application.StartupPath, @"../../")) + "Orders.xml";
if (File.Exists(parentOfStartupPath))
{
    // file found
}
1

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);
2
  • 2
    This fails in so many cases. What if the name of the folder is just a, for example? What if the path looks like this C:\Folderame3\Folderame2\Folderame\...?
    – 41686d6564
    May 6, 2018 at 19:24
  • if folder name is just a search "\\a\\" or \\a if its last
    – Taran
    May 7, 2018 at 3:03
1

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

Path parsing via System.IO.Directory.GetParent is possible, but would require to run same function multiple times.

Slightly simpler approach is to threat path as a normal string, split it by path separator, take out what is not necessary and then recombine string back.

var upperDir = String.Join(Path.DirectorySeparatorChar, dir.Split(Path.DirectorySeparatorChar).SkipLast(2));

Of course you can replace 2 with amount of levels you need to jump up.

Notice also that this function call to Path.GetFullPath (other answers in here) will query whether path exists using file system. Using basic string operation does not require any file system operations.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.