HttpContext.Current.Server.MapPath("/") 未将对象设置到对象的实例异常。

多线程中的System.Web.HttpContext.Current.Server.MapPath("/")

多线程中Server.MapPath会失效。。。

 网上找到几种解决方法,现在整理如下:

第一种:

System.Web.HttpContext.Current.Server.MapPath("/")  这个常用来表示网站的根目录,但是在多线程中,会发生未将对象引用设置到对象的实例。 所以不要分布在不同的类中,尽量在一个全局位置,然后其它类共用这个,毕竟网站的目录是不会改变的,可以用一个静态变量表示。

该方法:不太好;

第二种:

如果需要是WEB应用的目录下就很好办啊。假设web根目录为:c:\www,而DB放在www目录下的话则可以这样。  System.AppDomain.CurrentDomain.BaseDirectory.ToString() + ConfigurationManager.AppSettings["dbPath"]就可以了
我找到办法了,就是上面的

这个是一种方法,就是将路径下载配置文件中从配置文件读取,感觉还行。

第三种:

在多线程里面使用HttpContext.Current,HttpContext.Current是得到null的.    20150703 解释下为什么当前请求上下文会为null,因为多线程情况下,当前线程可能并非http请求处理线程,根本没发生请求,所以无法获取到HttpContext就是null.

这么用:       

  public static string MapPath(string strPath)
        {
            if (HttpContext.Current != null)
            {
                return HttpContext.Current.Server.MapPath(strPath);//有http请求
            }
            else //非web程序引用          
            {
                strPath = strPath.Replace("/", "\\");
                if (strPath.StartsWith("\\"))
                {
                    //strPath = strPath.Substring(strPath.IndexOf('\\', 1)).TrimStart('\\');                            strPath = strPath.TrimStart('\\');                
                }
                return System.IO.Path.Combine(AppDomain.CurrentDomain.BaseDirectory, strPath);
            }
        }

  

  

这个方法在csdn的帖子里,很多人都说很赞,我使用了该方法,该方法确实很好用。亲自测试很好用。

okok,总结完毕,希望对你也有用。

原文地址:https://www.cnblogs.com/Tpf386/p/3525121.html