C# 绝对到相对路径
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/13266756/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Absolute to Relative path
提问by Markus
I'm getting a file from an OpenFileDialog which returns a string with the absolute path to the selected file. Now I want that path as a relative path to a given path (in this case the path to my application).
我从 OpenFileDialog 获取一个文件,它返回一个字符串,其中包含所选文件的绝对路径。现在我希望该路径作为给定路径的相对路径(在这种情况下是我的应用程序的路径)。
So let's say I get a path to the file:
c:\myDock\programming\myProject\Properties\AssemblyInfo.cs
所以假设我得到了文件的路径:
c:\myDock\programming\myProject\Properties\AssemblyInfo.cs
and my application is located in
我的应用程序位于
c:\myDock\programming\otherProject\bin\Debug\program.exe
c:\myDock\programming\otherProject\bin\Debug\program.exe
then I want the result:
然后我想要结果:
..\..\..\myProject\Properties\AssemblyInfo.cs
..\..\..\myProject\Properties\AssemblyInfo.cs
采纳答案by Sisyphe
The Uriclass has a MakeRelativeUrimethod that can help.
本Uri类有一个MakeRelativeUri方法,可以帮助。
public static string MakeRelative(string filePath, string referencePath)
{
var fileUri = new Uri(filePath);
var referenceUri = new Uri(referencePath);
return Uri.UnescapeDataString(referenceUri.MakeRelativeUri(fileUri).ToString()).Replace('/', Path.DirectorySeparatorChar);
}
var result = MakeRelative(@"C:\dirName\dirName2\file.txt", @"C:\dirName\");

