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

.NET跨Windows与Linux传输数据时的路径分隔符兼容问题求解

解决方案

方案1:统一使用URI格式路径(兼容性最高,推荐)

URI规范默认使用正斜杠作为路径分隔符,你只需要在写入端把生成的相对路径转为URI格式统一存储,读取端再适配当前系统的分隔符即可,完全不会误伤Linux下文件名中合法的反斜杠:

写入端(任意系统)示例代码:

foreach (var file in files)
{
    var relativeDir = Path.GetRelativePath(rootPath, Path.GetDirectoryName(file));
    // 转为相对URI,自动统一为正斜杠格式
    var uri = new Uri(relativeDir, UriKind.Relative);
    fileData.Add(new FileData
    {
        FileName = Path.GetFileName(file),
        Path = uri.ToString()
    });
}

读取端(任意系统)示例代码:

foreach(var file in fileData)
{
    // 仅把存储的正斜杠替换为当前系统的目录分隔符,不会动任何反斜杠字符
    var adjustedPath = file.Path.Replace('/', Path.DirectorySeparatorChar);
    var fullPath = Path.Combine(rootPath, adjustedPath, file.FileName);
    // 后续创建目录、文件逻辑
}

方案2:.NET 6+ 原生API直接处理

如果你的项目可以升级到.NET 6及以上版本,Path类已经提供了ReplaceDirectorySeparators方法,直接就能实现分隔符统一:

// 写入端统一转为正斜杠存储
var relativePath = Path.GetRelativePath("./folder", "./folder/sf1/sf2")
    .ReplaceDirectorySeparators('/');

// 读取端转为当前系统的分隔符
var localRelativePath = relativePath.ReplaceDirectorySeparators(Path.DirectorySeparatorChar);

方案3:JSON转换器全局适配(无侵入业务代码)

如果你用Newtonsoft.Json或者System.Text.Json做序列化,可以写一个路径专属的JSON转换器,序列化时自动统一分隔符,反序列化时自动适配当前系统,完全对业务逻辑透明:

public class CrossPlatformPathConverter : JsonConverter<string>
{
    public override void WriteJson(JsonWriter writer, string value, JsonSerializer serializer)
    {
        // 序列化时统一转为正斜杠
        writer.WriteValue(value.Replace(Path.DirectorySeparatorChar, '/'));
    }

    public override string ReadJson(JsonReader reader, Type objectType, string existingValue, bool hasExistingValue, JsonSerializer serializer)
    {
        var rawValue = reader.Value?.ToString();
        return string.IsNullOrEmpty(rawValue) ? rawValue : rawValue.Replace('/', Path.DirectorySeparatorChar);
    }
}

// 只需要给FileData的Path字段加个特性即可,不用改其他业务代码
public class FileData
{
    [JsonConverter(typeof(CrossPlatformPathConverter))]
    public string Path { get; set; }
    public string FileName { get; set; }
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.08 08:24:03