Zhaoxin Guo

Don't lose hope. You never know what tomorrow will bring.

C# .NET Core Linux、Windows统一文件路径解决方法

我们上传或者下载时需要保存在指定目录,处理windows和linux目录路径问题:

 

//方案1  运行时自带
var path1 = Path.Combine("xxx", "yyy", "zzz");
//方案2  反斜杠 两个平台都可以用
var path2 = ("xxx/yyy/zzz");
//方案3 根据不同环境生成不同文件路径,GetRuntimeDirectory 自己编写
//判断平台环境,路径可以任意格式"xxx/yyy\\zzz" 
//实际上多个开发协同的时候就是比较混乱,开发环境都没问题,集成的时候报错频繁
var path3 = GetRuntimeDirectory("xxx/yyy/zzz");

 

1、需要引用 System.Runtime.InteropServices

public static string GetRuntimeDirectory(string path)
{
    //ForLinux
    if (IsLinuxRunTime())
        return GetLinuxDirectory(path);
    //ForWindows
    if (IsWindowRunTime())
        return GetWindowDirectory(path);
    return path;
}

//OSPlatform.Windows监测运行环境
public static bool IsWindowRunTime()
{  
    return System.Runtime.InteropServices.RuntimeInformation.IsOSPlatform(OSPlatform.Windows);
}

//OSPlatform.Linux运行环境
public static bool IsLinuxRunTime()
{
    return System.Runtime.InteropServices.RuntimeInformation.IsOSPlatform(OSPlatform.Linux);
}

public static string GetLinuxDirectory(string path)
{
    string pathTemp = Path.Combine(path);
    return pathTemp.Replace("\\", "/");
}
public static string GetWindowDirectory(string path)
{
    string pathTemp = Path.Combine(path);
    return pathTemp.Replace("/", "\\");
}

 

posted @ 2020-12-21 20:18  "郭召欣"  阅读(3437)  评论(2编辑  收藏  举报