Server.MapPath(string sFilePath) 報未將對象引用到實例異常


System.Web.HttpContext.Current.Server.MapPath(string sfilePath)將虛擬路徑轉換成物理路徑。這個必須在aspx或者MVC中Action調用才行,即必須是有HttpContext.Current對象。但是好像在線程執行任務中若是調用了System.Web.HttpContext.Current.Server.MapPath(string sfilePath)就會報異常,因為沒有HttpContext.Current對象。

System.AppDomain.CurrentDomain.BaseDirectory:應用程序根路徑,在沒有HttpContext.Current對象時可以使用

遇到此問題 之前用MVC的Controller中Action去調用就行,但是在Global的 Application_Start調用System.Web.HttpContext.Current.Server.MapPath(string sfilePath) 就會引發“未將對象引用設置到對象的實例”異常,所以必須用System.AppDomain.CurrentDomain.BaseDirectory獲取根路徑再拼接上想要的文件路徑和文件名稱就可以解決。
//string sLogPath = System.Web.HttpContext.Current.Server.MapPath("/Log/PaymentLog/AlipayLog/" + DateTime.Now.ToString("yyyy-MM-dd") + ".txt");
string sLogPath = System.AppDomain.CurrentDomain.BaseDirectory.ToString() +"/Log/PaymentLog/AlipayLog/" + DateTime.Now.ToString("yyyy-MM-dd") + ".txt";
using (FileStream fileStream = new FileStream(sLogPath, FileMode.Create, FileAccess.ReadWrite))
            {
                using (StreamWriter writer = new StreamWriter(fileStream))
                {
                       //todo:業務邏輯
                }
            }

 

 


免責聲明!

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



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