You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

C# .NET 6中如何获取带正斜杠及尾斜杠的相对路径?

获取特定格式的相对路径

.NET 框架中没有内置函数可以直接生成带正斜杠且末尾强制添加斜杠的相对路径。System.IO.Path.GetRelativePath 方法的设计是基于系统默认路径分隔符(Windows 下为反斜杠)返回结果,且不会自动在末尾追加路径分隔符。

可行的解决方案

你提供的手动处理方案是有效的,也可以根据需求做小幅优化:

  1. 通用跨平台写法
    用框架提供的路径分隔符常量代替硬编码字符,适配不同操作系统:

    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/
    
  2. Windows 环境简化写法
    如果确定只在 Windows 环境下运行,你原本的写法完全没问题:

    var desiredOutput = $"{relativePath.Replace('\\', '/')}/";
    
  3. 避免末尾多斜杠的处理
    若要确保无论原路径是否带斜杠,最终结果都只有一个末尾斜杠,可以先修剪再添加:

    var normalizedRelative = relativePath.Replace('\\', '/').TrimEnd('/');
    var desiredOutput = $"{normalizedRelative}/";
    

内容的提问来源于stack exchange,提问作者CrazyEight

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.17 11:57:11