我們上傳或者下載時需要保存在指定目錄,處理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("/", "\\"); }