C# 将绝对路径转换为相对路径

引言

 

在档次中常供给将相对路径,转换为相对路径,来扩大程序相关配置的的八面见光(不用因为全体挪个岗位就造成我们的程序不可能健康工作)

 

杀鸡取蛋难题方法

 

投机写代码化解:

private string RelativePath(string absolutePath, string relativeTo)
        {
            string[] absoluteDirectories = absolutePath.Split('\\');
            string[] relativeDirectories = relativeTo.Split('\\');

            //Get the shortest of the two paths
            int length = absoluteDirectories.Length < relativeDirectories.Length ? absoluteDirectories.Length : relativeDirectories.Length;

            //Use to determine where in the loop we exited
            int lastCommonRoot = -1;
            int index;

            //Find common root
            for (index = 0; index < length; index++)
                if (absoluteDirectories[index] == relativeDirectories[index])
                    lastCommonRoot = index;
                else
                    break;

            //If we didn't find a common prefix then throw
            if (lastCommonRoot == -1)
                throw new ArgumentException("Paths do not have a common base");

            //Build up the relative path
            StringBuilder relativePath = new StringBuilder();

            //Add on the ..
            for (index = lastCommonRoot + 1; index < absoluteDirectories.Length; index++)
                if (absoluteDirectories[index].Length > 0)
                    relativePath.Append("..\\");

            //Add on the folders
            for (index = lastCommonRoot + 1; index < relativeDirectories.Length - 1; index++)
                relativePath.Append(relativeDirectories[index] + "\\");
            relativePath.Append(relativeDirectories[relativeDirectories.Length - 1]);

            return relativePath.ToString();
        }

 

通过C#中U奥迪Q7I类来化解:

System.Uri uri1 = new Uri(@"C:\filename.txt");
System.Uri uri2 = new Uri(@"C:\mydirectory\anotherdirectory\");

Uri relativeUri = uri2.MakeRelativeUri(uri1);

Console.WriteLine(relativeUri.ToString());

 

 

参考文献

 

http://msdn.microsoft.com/en-us/library/system.uri.makerelativeuri(v=vs.110).aspx

 

相对路径

相关文章