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("/", "\\");
}

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM