C# .NET 6中如何获取带正斜杠及尾斜杠的相对路径?
获取特定格式的相对路径
.NET 框架中没有内置函数可以直接生成带正斜杠且末尾强制添加斜杠的相对路径。System.IO.Path.GetRelativePath 方法的设计是基于系统默认路径分隔符(Windows 下为反斜杠)返回结果,且不会自动在末尾追加路径分隔符。
可行的解决方案
你提供的手动处理方案是有效的,也可以根据需求做小幅优化:
通用跨平台写法
用框架提供的路径分隔符常量代替硬编码字符,适配不同操作系统:var from = @"C:\This\is\my\path\folder1"; var to = @"C:\This\is\my\path\folder2\folder3"; var relativePath = Path.GetRelativePath(from, to); var desiredOutput = $"{relativePath.Replace(Path.DirectorySeparatorChar, Path.AltDirectorySeparatorChar)}{Path.AltDirectorySeparatorChar}"; Console.WriteLine(desiredOutput); // 输出: ../folder2/folder3/Windows 环境简化写法
如果确定只在 Windows 环境下运行,你原本的写法完全没问题:var desiredOutput = $"{relativePath.Replace('\\', '/')}/";避免末尾多斜杠的处理
若要确保无论原路径是否带斜杠,最终结果都只有一个末尾斜杠,可以先修剪再添加:var normalizedRelative = relativePath.Replace('\\', '/').TrimEnd('/'); var desiredOutput = $"{normalizedRelative}/";
内容的提问来源于stack exchange,提问作者CrazyEight
相关产品推荐
相关产品推荐

