·您现在的位置: 云翼网络 >> 文章中心 >> 网站建设 >> 网站建设开发 >> ASP.NET网站开发 >> Server.MapPath(string sFilePath) 报未将对象引用到实例异常

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

作者:佚名      ASP.NET网站开发编辑:admin      更新时间:2022-07-23

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