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:业务逻辑
                    }
                }
     
  • 相关阅读:
    poj3107 Godfather
    poj1655 Balancing Act
    bzoj2073 PRZ
    bzoj1688 疾病管理
    BZOJ——1607: [Usaco2008 Dec]Patting Heads 轻拍牛头
    BZOJ——1606: [Usaco2008 Dec]Hay For Sale 购买干草
    BZOJ——1649: [Usaco2006 Dec]Cow Roller Coaster
    BZOJ——2096: [Poi2010]Pilots
    洛谷—— P1785 漂亮的绝杀
    NOIP 2012 提高组 DAY1 T2 国王游戏
  • 原文地址:https://www.cnblogs.com/hewencong/p/4227987.html
Copyright © 2011-2022 走看看