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#中URI类来解决:
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
作者:旭东
出处:http://www.cnblogs.com/HQFZ
关于作者:专注于微软平台项目架构、管理和企业解决方案。现主要从事WinForm、ASP.NET、WPF、WCF、等方面的项目开发、架构、管理。如有问题或建议,请不吝指教!
本文版权归作者,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文连接。如有问题,可以联系我,非常感谢。
如果您该文觉得不错或者对你有帮助,请点下推荐,让更多的朋友看到,谢谢!