Server.MapPath(string sFilePath) 报未将对象引用到实例异常

王朝学院·作者佚名  2016-05-21
窄屏简体版  字體: 小  |  中  |  大  |  超大  

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:业务逻辑 } }

 
 
免责声明:本文为网络用户发布,其观点仅代表作者个人观点,与本站无关,本站仅提供信息存储服务。文中陈述内容未经本站证实,其真实性、完整性、及时性本站不作任何保证或承诺,请读者仅作参考,并请自行核实相关内容。
 
© 2005- 王朝網路 版權所有 導航