源码网商城,靠谱的源码在线交易网站 我的订单 购物车 帮助

源码网商城

C#绝对路径拼接相对路径的实例代码

  • 时间:2021-05-28 08:23 编辑: 来源: 阅读:
  • 扫一扫,手机访问
摘要:C#绝对路径拼接相对路径的实例代码
做项目时发现Path.Combine方法只能支持傻瓜式的目录拼接
[u]复制代码[/u] 代码如下:
//绝对路径 string absolutePath = @"C:\Program Files\Internet Explorer"; //相对路径 string relativePath = @"..\TestPath\"; //预计拼接结果 string splicingResult = string.Empty; Console.WriteLine(string.Format("Path.Combine(\"{0}\",\"{1}\")=\"{2}\"", absolutePath, relativePath, Path.Combine(absolutePath, relativePath)));
输出结果为: [img]http://files.jb51.net/file_images/article/201303/2013318111059967.png[/img] 发现并没有按照想像的分辨出相对路径和绝对路径,所以只好用正则匹配了相对路径进行重新拼接,以下方法只支持绝对路径+相对路径的方式 //绝对路径 string absolutePath = @"C:\Program Files\Internet Explorer"; //相对路径 string relativePath = @"..\TestPath\"; //预计拼接结果 string splicingResult = string.Empty; Console.WriteLine(string.Format("Path.Combine(\"{0}\",\"{1}\")=\"{2}\"", absolutePath, relativePath, Path.Combine(absolutePath, relativePath))); if (!Path.IsPathRooted(relativePath)) {     //匹配相对路径,匹配需要向上推的目录层数     Regex regex = new Regex(@"^\\|([..]+)");     int backUp = regex.Matches(relativePath).Count;     List<string> pathes = absolutePath.Split("\\".ToCharArray()).ToList();     pathes.RemoveRange(pathes.Count - backUp, backUp);     //匹配文件名,匹配需要附加的目录层数     regex = new Regex(@"^\\|([a-zA-Z0-9]+)");     MatchCollection matches = regex.Matches(relativePath);     foreach (Match match in matches)     {         pathes.Add(match.Value);     }     //驱动器地址取绝对路径中的驱动器地址     pathes[0] = Path.GetPathRoot(absolutePath);     foreach (string p in pathes)     {         splicingResult = Path.Combine(splicingResult, p);     } } Console.WriteLine(string.Format("Absolute Path={0}",absolutePath)); Console.WriteLine(string.Format("Relative Path={0}", relativePath)); Console.WriteLine(string.Format("Path.Combine(\"{0}\",\"{1}\")=\"{2}\"", absolutePath, relativePath, splicingResult)); Console.ReadLine(); 输出结果: [img]http://files.jb51.net/file_images/article/201303/2013318110943077.png[/img]
  • 全部评论(0)
联系客服
客服电话:
400-000-3129
微信版

扫一扫进微信版
返回顶部