How to Navigate a Few Folders Up

How to navigate one folder up from current file path?

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

Moving up a folder from the executable

Can you try this?

    static void Main(string[] args)
{
string cur = Environment.CurrentDirectory;
Console.WriteLine(cur);
string parent1 = Path.Combine(cur, @"..\");
Console.WriteLine(new DirectoryInfo(parent1).FullName);
string parent2 = Path.Combine(cur, @"..\..\");
Console.WriteLine(new DirectoryInfo(parent2).FullName);
Console.ReadLine();
}

Navigating back and forward at once in path C#

. refers to the current directory
.. refers to the directory one level above the current

In your example:

..\..\..\..\..\..\2\3\4\5\test.xml

This moves up to the a directory then traverses down to 5 where your file resides.

Something that might be helpful to test your path and ensure you are where you think you are is this:

string currentPath = Path.GetFullPath(relativePath);

And then check the value of currentPath, if it winds up somewhere you didn't expect you can debug your path traversal rather than your code.

How to go back multiple times in a directory path?

How about this:

@echo off
SET currentDirectory=%~dp0
PUSHD %CD%
CD ..
CD ..
SET MNIST_DIR=%CD%
POPD
ECHO %MNIST_DIR%
PAUSE

This generates the output N:\caffe-master\.

EDIT: By using PUSHD %CD% and POPD at the end of the script we can ensure that we will always end up in the original directory.

Go up several directories in linux

cd ../../../../../../../

Also another useful navigation tip is if for example lets say you keep switching from a directory (call it A) to another (call it B) that's 7 directories up, in your case.

So if you're in directory A:

A> cd ../../../../../../../
B> // Now you're in directory B and want to go back to A
B> cd -

That will move right back to directory A. - expands to the previous directory you were in.

How to go one level higher in the file directory when reading a txt file in C#?

File.Read(@"..\doc.txt");

Will achieve this, the reason to add @ at the start is to show that you're writing a string literal which will allow you to use '\' without needing to escape it. the ".." part is how you tell the document to go into the parent directory.



Related Topics



Leave a reply



Submit