本文介绍了获取相对路径当前工作目录?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在写一个控制台实用程序执行上的命令行中指定文件的一些处理,但是我碰到我无法通过谷歌/堆栈&NBSP解决问题;溢出。如果指定了一个完整路径,包括驱动器号的,我怎么重新格式化路径是相对于当前的工作目录?
I'm writing a console utility to do some processing on files specified on the commandline, but I've run into a problem I can't solve through Google/Stack Overflow. If a full path, including drive letter, is specified, how do I reformat that path to be relative to the current working directory?
有一定相似VirtualPathUtility.MakeRelative功能的东西,但如果有,它躲开我。
There must be something similar to the VirtualPathUtility.MakeRelative function, but if there is, it eludes me.
推荐答案
如果你不介意被切换斜线,你可以[AB]使用乌里
:
If you don't mind the slashes being switched, you could [ab]use Uri
:
Uri file = new Uri(@"c:\foo\bar\blop\blap.txt");
// Must end in a slash to indicate folder
Uri folder = new Uri(@"c:\foo\bar\");
string relativePath =
Uri.UnescapeDataString(
folder.MakeRelativeUri(file)
.ToString()
.Replace('/', Path.DirectorySeparatorChar)
);
作为一个函数/方法:
string GetRelativePath(string filespec, string folder)
{
Uri pathUri = new Uri(filespec);
// Folders must end in a slash
if (!folder.EndsWith(Path.DirectorySeparatorChar.ToString()))
{
folder += Path.DirectorySeparatorChar;
}
Uri folderUri = new Uri(folder);
return Uri.UnescapeDataString(folderUri.MakeRelativeUri(pathUri).ToString().Replace('/', Path.DirectorySeparatorChar));
}
这篇关于获取相对路径当前工作目录?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!