System.Web.HttpContext.Current.Server.MapPath(string sfilePath)將虛擬路徑轉(zhuǎn)換成物理路徑。這個必須在aspx或者MVC中Action調(diào)用才行,即必須是有HttpContext.Current對象。但是好像在線程執(zhí)行任務(wù)中若是調(diào)用了System.Web.HttpContext.Current.Server.MapPath(string sfilePath)就會報異常,因為沒有HttpContext.Current對象。
System.AppDomain.CurrentDomain.BaseDirectory:應(yīng)用程序根路徑,在沒有HttpContext.Current對象時可以使用
遇到此問題 之前用MVC的Controller中Action去調(diào)用就行,但是在Global的 application_Start調(diào)用System.Web.HttpContext.Current.Server.MapPath(string sfilePath) 就會引發(fā)“未將對象引用設(shè)置到對象的實例”異常,所以必須用System.AppDomain.CurrentDomain.BaseDirectory獲取根路徑再拼接上想要的文件路徑和文件名稱就可以解決。//string sLogPath = System.Web.HttpContext.Current.Server.MapPath("/Log/PaymentLog/Alaccess.ReadWrite)) { using (StreamWriter writer = new StreamWriter(fileStream)) { //todo:業(yè)務(wù)邏輯 } }新聞熱點
疑難解答