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
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\");
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With