系统如何沿着一个路径向后走

huangapple go评论60阅读模式
英文:

How does the system go backward one path

问题

当前路径是 C:\Users\USERNAME\OneDrive\Desktop\Pro\Professional

我如何将它设置为 C:\Users\USERNAME\OneDrive\Desktop\Pro

但我不想通过写字符串来设置它回去,我希望系统能够理解它所在的位置并向后移动。

简单来说,我希望它像 Windows 命令提示符中的 cd.. 命令一样。

英文:

It's current path is C:\Users\USERNAME\OneDrive\Desktop\Pro\Professional

How do i set it to C:\Users\USERNAME\OneDrive\Desktop\Pro

But I don't set by writing string to set it back I want the system to understand where it is and go backwards.

Simply put I want it to be like the cd.. command in Windows CMD.

答案1

得分: 2

获取当前目录,使用

var currentDirectory = Directory.GetCurrentDirectory();

要获取父目录,使用

var parentDirectory = Path.GetDirectoryName(currentDirectory);

最后,要设置当前目录:

Directory.SetCurrentDirectory(parentDirectory);
英文:

To get the current directory, use

var currentDirectory = Directory.GetCurrentDirectory();

To get the parent directory, use

var parentDirectory = Path.GetDirectoryName(currentDirectory);

And finally to set the current directory:

Directory.SetCurrentDirectory(parentDirectory);

答案2

得分: 0

System.IO 中有一个叫做 Path.GetDirectoryName 的方法。它会以你提供的路径作为输入,并返回该路径的父目录。

示例:

string path = "C:\Users\USERNAME\OneDrive\Desktop\Pro\Professional";
string parentDirectory = Path.GetDirectoryName(path);

在这里,parentDirectory 现在包含 C:\Users\USERNAME\OneDrive\Desktop\Pro

如果你想向上多级,你可以多次调用;例如,

string path = @"C:\Users\USERNAME\OneDrive\Desktop\Pro\Professional";
string parentDirectory = Path.GetDirectoryName(Path.GetDirectoryName(path));

parentDirectory 现在包含 C:\Users\USERNAME\OneDrive\Desktop

英文:

There is a method in System.IO called Path.GetDirectoryName. This would take your path as input and return the parent directory of the path which you have given.

Example:

string path = "C:\Users\USERNAME\OneDrive\Desktop\Pro\Professional";
string parentDirectory = Path.GetDirectoryName(path);

Here, the parentDirectory now contains C:\Users\USERNAME\OneDrive\Desktop\Pro.

If you want to go up multiple levels, you can call multiple times; e.g.,

string path = @"C:\Users\USERNAME\OneDrive\Desktop\Pro\Professional";
string parentDirectory = Path.GetDirectoryName(Path.GetDirectoryName(path));

The parentDirectory now contains C:\Users\USERNAME\OneDrive\Desktop.

huangapple
  • 本文由 发表于 2023年2月18日 15:48:06
  • 转载请务必保留本文链接:https://go.coder-hub.com/75491925.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定