.net core获取根目录并转化字符串
在.net core中有一个IWebHostEnvironment接口(在低版本中为IHostEnvironment)
IWebHostEnvironment里面有一个ContentRootPath(根目录)和WebRootPath(根目录+wwwroot)
为了区别windows环境和普通路径环境,需要进行判断(windows操作系统环境下,路径均为\\)
.net core也提供了判断的语法,
public static bool _windows = RuntimeInformation.IsOSPlatform(OSPlatform.Windows);
通过IsOSPlatform可以判断,当前环境是否是指定的操作系统环境,除了windows,还可以是Linux,unix等
这样就可以转换从windows获取的根目录了
public static string ReplacePath(this string path) { if(string.IsNullOrEmpty(path)) return ""; if (_windows) return path.Replace("/", "\\"); return path.Replace("\\", "/"); }
最后转换代码:
Path.Combine(environment.ContentRootPath, "").ReplacePath();
记录编程的点滴,体会学习的乐趣