我试图将一些Python代码移植到.NET,我想知道在.NET中是否存在以下Python函数的等价物,或者某些具有相同功能的代码片段.
os.path.split()
os.path.basename()
Run Code Online (Sandbox Code Playgroud)
编辑
Python中的os.path.basename()返回os.path.split的尾部,而不是System.IO.Path.GetPathRoot(path)的结果
我认为以下方法创建了一个合适的os.path.split函数端口,欢迎任何调整.它遵循http://docs.python.org/library/os.path.html中对os.path.split的描述,我认为尽可能多.
public static string[] PathSplit(string path)
{
string head = string.Empty;
string tail = string.Empty;
if (!string.IsNullOrEmpty(path))
{
head = Path.GetDirectoryName(path);
tail = path.Replace(head + "\\", "");
}
return new[] { head, tail };
}
Run Code Online (Sandbox Code Playgroud)
我不确定我返回头部和尾部的方式,因为我真的不想通过参数传递头部和尾部的方法.
你正在寻找System.IO.Path班级.
它有许多功能可用于获得相同的功能.
Path.GetDirectoryName(string)String.Split(...)在实际路径名上使用.您可以通过以下方式获取OS Dependent分离器Path.PathSeparator.os.path.split你想要的文件名,请使用Path.GetFileName(string).请注意:您可以System.IO使用Visual Studio中的对象浏览器(Ctrl + Alt + J)浏览命名空间的所有成员.从这里开始mscorlib- > System.IO所有课程都可以在那里找到.
这就像Intellisense破解:)