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