Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to navigate one folder up from current file path?

Tags:

c#

I need to navigate one folder up from the current path of a file and save the same file there. How can I strip one level from the directory path? Thank you!

C:\Users\stacy.zim\AppData\Local\Temp\ICLocal\e53486af-7e5e-4c54-b9dc-d15cb55f3f55.pdf

The file will be saved to below.

C:\Users\stacy.zim\AppData\Local\Temp\e53486af-7e5e-4c54-b9dc-d15cb55f3f55.pdf

like image 737
Jyina Avatar asked Jun 22 '15 23:06

Jyina


2 Answers

Actually it is called Parent for "One Folder Up"

System.IO.DirectoryInfo.Parent

// Method 1 Get by file
var file = new FileInfo(@"C:\Users\stacy.zim\AppData\Local\Temp\ICLocal\e53486af-7e5e-4c54-b9dc-d15cb55f3f55.pdf");
var parentDir = file.Directory == null ? null : file.Directory.Parent; // null if root
if (parentDir != null)
{
    // Do something with Path.Combine(parentDir.FullName, filename.Name);
}

System.IO.Directory.GetParent()

// Method 2 Get by path
var parentDir = Directory.GetParent(@"C:\Users\stacy.zim\AppData\Local\Temp\ICLocal\");
like image 197
Eric Avatar answered Oct 13 '22 07:10

Eric


string path = @"C:\Users\stacy.zim\AppData\Local\Temp\ICLocal\e53486af-7e5e-4c54-b9dc-d15cb55f3f55.pdf"
string directory = Path.GetDirectoryName(path); //without file name
string oneUp = Path.GetDirectoryName(directory); // Temp folder
string fileOneUp = Path.Combine(oneUp, Path.GetFileName(path));

Just be careful if the original file is in root folder - then the oneUp will be null and Path.Combine will throw an exception.

Edit:

In the code above, I split the commands on separate lines for clarity. It could be done in one line:

Path.Combine(Path.GetDirectoryName(Path.GetDirectoryName(path)), Path.GetFileName(path));

Or, as @AlexeiLevenkov suggest, you can use .. to go up one directory. In that case, you could do:

Path.Combine(Path.GetDirectoryName(path), @"..\"+Path.GetFileName(path));

which will give you the .. in your path - if you don't want that, run Path.GetFullPath on the result. Again, you need to be careful if your original file is in the root folder - unlike the first approach, which will throw an exception, this will just give you the same path.

like image 40
vesan Avatar answered Oct 13 '22 07:10

vesan