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

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

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

代码经过验证可用。

cs 复制代码
       /// <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;
                else
                    break;
            }

            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"这样的结果,可以存储到配置文件中,在使用时如果需要可以转成绝对路径。

相关推荐
专注API从业者4 小时前
Python + 淘宝 API 开发:自动化采集商品数据的完整流程
大数据·运维·前端·数据挖掘·自动化
烛阴5 小时前
TypeScript高手密技:解密类型断言、非空断言与 `const` 断言
前端·javascript·typescript
好望角雾眠5 小时前
第一阶段C#基础-10:集合(Arraylist,list,Dictionary等)
笔记·学习·c#
样子20185 小时前
Uniapp 之renderjs解决swiper+多个video卡顿问题
前端·javascript·css·uni-app·html
Nicholas685 小时前
flutterAppBar之SystemUiOverlayStyle源码解析(一)
前端
黑客飓风6 小时前
JavaScript 性能优化实战大纲
前端·javascript·性能优化
emojiwoo7 小时前
【前端基础知识系列六】React 项目基本框架及常见文件夹作用总结(图文版)
前端·react.js·前端框架
张人玉8 小时前
XML 序列化与操作详解笔记
xml·前端·笔记
杨荧8 小时前
基于Python的宠物服务管理系统 Python+Django+Vue.js
大数据·前端·vue.js·爬虫·python·信息可视化
YeeWang8 小时前
🎉 Eficy 让你的 Cherry Studio 直接生成可预览的 React 页面
前端·javascript