zoukankan      html  css  js  c++  java
  • 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:业务逻辑
                    }
                }
     
  • 相关阅读:
    iOS代码段整理
    Git命令行
    Vue开发系列四- 网络请求库vue-resource的使用
    Vue开发系列三 调试
    Vue开发系列三-打包
    Vue开发系列二 熟悉项目结构
    错误及经验记录
    cocopods sh 项目运行权限问题
    关于添加UITextField添加输入内容判定导致九宫格键盘无法使用问题
    catagory添加属性
  • 原文地址:https://www.cnblogs.com/hewencong/p/4227987.html
Copyright © 2011-2022 走看看