C#相对路径转绝对路径,绝对路径转相对路径
来源:互联网 发布:2016网络暴力案例 编辑:程序博客网 时间:2024/05/29 18:55
1.绝对路径转相对路径
绝对转相对似乎C#没有提供实现,需要自己写,这里摘选了一位博友的实现方法:
string RelativePath(string absolutePath, string relativeTo) { //from - www.cnphp6.com 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(); }
调用:
static void Main(string[] args){ var path = RelativePath(@"D:\MyProj\Release", @"D:\MyProj\Log\MyFile.txt"); Console.WriteLine(path);//print ..\Log\MyFile.txt Console.Read();}
2.相对路径转绝对路径
可以直接用.Net自己的Path.GetFullPath转换。用SetCurrentDirectory改变当前比较路径
static void Main(string[] args){ var relativePath = @"..\..\Release"; //Directory.SetCurrentDirectory(...) Console.WriteLine(Path.GetFullPath(relativePath)); Console.Read();}
阅读全文
0 0
- C#相对路径转绝对路径,绝对路径转相对路径
- 相对路径转绝对路径
- C#中绝对路径转相对路径
- URL相对路径转绝对路径
- URL相对路径转绝对路径
- C# 相对路径转绝对路径
- 将相对路径转绝对路径
- Java相对路径/绝对路径总结[转]
- Java相对路径/绝对路径总结 (转)
- Java相对路径/绝对路径总结(转)
- Java相对路径/绝对路径总结(转)
- 【转】 java中的相对路径和绝对路径
- 绝对路径与相对路径(转)
- Java相对路径/绝对路径总结(转)
- Java相对路径/绝对路径总结(转)
- Linux: shell相对路径转绝对路径
- Java相对路径/绝对路径总结(转)
- Java相对路径/绝对路径总结(转)
- hdu 1728 逃离迷宫
- kafka多线程消费和手动提交offset,新版java api
- 抽象类、接口和内部类(上)
- ThinkPhp学习笔记-如何定义Template模板路径
- ACM Contest and Blackout
- C#相对路径转绝对路径,绝对路径转相对路径
- Codeforces Round #422 (Div. 2) C. Hacker, pack your bags!
- 抽象类、接口和内部类(下)
- POJ 3984 迷宫问题
- Java-Java反射
- HDU 2553 N皇后问题
- 51nod 1238 最小公倍数之和 V3
- MFC exe替换大、中、小图标方法
- 《深入探索Android热修复技术原理》安卓热修复原理宝典出炉,阿里技术大牛联袂推荐