当前位置: 首页 > news >正文

c#实现绝对路径和相对路径的转换

有时候需要实现绝对路径和相对路径的转换,其实在c#高一点的版本中已经实现了此功能的封装,但是在版本比较低的时候,比如.net4.6.1,则需要手动实现其中的一些逻辑。

下面这里提供了代码,其中获取相对路径实现了一个重载函数,一个是获取当前路径下的某绝对路径的相对路径,一个是获取某个路径下某绝对路径的相对路径。

代码经过验证可用。

       /// <summary>/// 将相对路径转换为绝对路径/// </summary>/// <param name="basePath">当前路径</param>/// <param name="relativePath">相对路径</param>/// <returns>绝对路径</returns>public static string GetAbsolutePath(string basePath, string relativePath){// 合并路径并标准化string combinedPath = Path.Combine(basePath, relativePath);return Path.GetFullPath(combinedPath);}/// <summary>/// 获取相对路径或者绝对路径/// </summary>/// <param name="path"></param>/// <param name="bRelative"></param>/// <returns></returns>public static string GetRelativePath(string path, bool bRelative){if (string.IsNullOrEmpty(path))return path;try{if (bRelative){// 当要求返回相对路径时if (!Path.IsPathRooted(path))return path; // 已经是相对路径直接返回string currentDir = Directory.GetCurrentDirectory();return GetRelativePath(currentDir, path);}else{// 当要求返回绝对路径时if (Path.IsPathRooted(path))return path; // 已经是绝对路径直接返回string currentDir = Directory.GetCurrentDirectory();return Path.GetFullPath(Path.Combine(currentDir, path));}}catch (Exception){return path; // 发生异常时返回原路径}}/// <summary>/// 返回相对路径/// </summary>/// <param name="basePath"></param>/// <param name="targetPath"></param>/// <returns></returns>public static string GetRelativePath(string basePath, string targetPath){// 统一路径分隔符basePath = basePath.Replace('/', '\\');targetPath = targetPath.Replace('/', '\\');string[] baseParts = basePath.Split('\\');string[] targetParts = targetPath.Split('\\');int commonRoot = -1;int minLength = Math.Min(baseParts.Length, targetParts.Length);// 查找共同根目录for (int i = 0; i < minLength; i++){if (string.Equals(baseParts[i], targetParts[i], StringComparison.OrdinalIgnoreCase))commonRoot = i;elsebreak;}if (commonRoot == -1)return targetPath; // 没有共同根目录,返回完整路径// 构建相对路径var relativePath = new System.Text.StringBuilder();// 添加返回上级目录部分for (int i = commonRoot + 1; i < baseParts.Length; i++){if (baseParts[i].Length > 0)relativePath.Append("..\\");}// 添加目标路径剩余部分for (int i = commonRoot + 1; i < targetParts.Length; i++){relativePath.Append(targetParts[i]);if (i < targetParts.Length - 1)relativePath.Append('\\');}return relativePath.ToString();}

至此,可以得到类似于 “..\\config\\file.txt”这样的结果,可以存储到配置文件中,在使用时如果需要可以转成绝对路径。

相关文章:

  • 【网络】每天掌握一个Linux命令 - netperf
  • 【题解-洛谷】P2935 [USACO09JAN] Best Spot S
  • 2025年5月一区SCI-状态优化算法Status-based Optimization-附Matlab免费代码
  • CVE-2017-12615源码分析与漏洞复现(Tomcat 任意文件上传)
  • 工程论文: TORL: Scaling Tool-Integrated RL
  • day28/60
  • 1005. Maximize Sum Of Array After K Negations
  • 如何用python读取大的xml文件,示例为1.9G的xml文件
  • HarmonyOS - UIObserver(无感监听)
  • Windows 安装以及配置Docker全流程 - Docker Toolbox
  • vibe coding 2025工具全景图
  • python打卡day51@浙大疏锦行
  • 如何利用测试Agent自动分析覆盖率报告与缺陷趋势
  • “十五五”时期智慧城市赋能全国一体化数据市场建设:战略路径与政策建议[ 注:本建议基于公开政策文件与行业实践研究,数据引用截至2025年6月11日。]
  • 剑指offer21——反转链表
  • 力扣上C语言编程题:最大子数组和(涉及数组)
  • Qwen3-Embedding-8B:文本嵌入界的“卷王”,多语言检索新标杆!
  • 嵌入式学习笔记 - C语言访问地址的方式,以及指针的进一步理解
  • 简单的五子棋实现简介
  • 6.11本日总结
  • 网站栏目做ip地址访问限制/优秀的软文广告欣赏
  • 陕西省网站备案/河南网站推广多少钱
  • wordpress获取新密码/seo推广平台
  • 前端做网站的兼职/公司网站模版
  • 投资网站建设/免费推广软件 推广帮手
  • 如何做网站聚合页/石家庄百度seo代理