当前位置: 首页 > 编程语言 > C#

如何创建相对于特定文件夹的绝对路径?分享

时间:2023-04-10 14:38:13 C#

如何制作相对于特定文件夹的绝对路径?例如,如何相对于此文件夹“C:RootFolderSubFolder”执行“C:RootFolderSubFolderMoreSubFolderLastFolderSomeFile.txt”如果预期结果是“MoreSubFolderLastFolderSomeFile.txt”是的,你可以这样做,简单,将你的路径视为对于URI:UrifullPath=newUri(@"C:RootFolderSubFolderMoreSubFolderLastFolderSomeFile.txt",UriKind.Absolute);UrirelRoot=newUri(@"C:RootFolderSubFolder",UriKind.Absolute);字符串relPath=relRoot.MakeRelativeUri(fullPath).ToString();//relPath==@"MoreSubFolderLastFolderSomeFile.txt"在您的示例中它只是absPath.Substring(relativeTo.Length)。更详细的例子需要从relativeTo返回几层,如下:"C:RootFolderSubFolderMoreSubFolderLastFolderSomeFile.txt""C:RootFolderSubFolderSiblingChild"制作相对路径的算法如下:最后结果如下:"....MoreSubFolderLastFolderSomeFile.txt”这是我的5美分,因为我没有为此目的使用任何特殊的Url类。在以下svn存储库中搜索makeRelative:https://sourceforge.net/p/syncproj/code/HEAD/tree/syncProj.cs#l976我将修复错误(如果有)。为什么所有这些复杂的解决方案都涉及Uri?真的吗?您不必等待第一个异常。简洁的。不需要任何额外的框架类。publicstaticstringBuildRelativePath(stringabsolutePath,stringbasePath){returnabsolutePath.Substring(basePath.Length);如果你不能总是添加或总是省略关闭System.IO.Path.DirectorySeparatorChar到你的字符串,或者你不能混合参数:以上是C#学习教程:Howtomakeanabsolutepathrelativetoa具体文件夹?如果分享的内容对你有用,需要进一步了解C#学习教程,希望你多多关注——basePath==null)返回null;absolutePath=absolutePath.Replace(System.IO.Path.DirectorySeparatorChar,'/');basePath=basePath.Replace(System.IO.Path.DirectorySeparatorChar,'/');如果(!basePath.EndsWith("/"))basePath+="/";如果(!absolutePath.EndsWith("/"))absolutePath+="/";if(absolutePath.Length)本文采集自网络,不代表立场,如涉及侵权,请点击右侧联系管理员删除。如需转载,请注明出处: