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

时间:2014-01-18 18:43:31   收藏:0   阅读:483

多线程中的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的.
这么用:         public static string MapPath(string strPath)         {             if (HttpContext.Current != null)             {                 return HttpContext.Current.Server.MapPath(strPath);             }             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,总结完毕,希望对你也有用。

原文:http://www.cnblogs.com/Tpf386/p/3525121.html

评论(0
© 2014 bubuko.com 版权所有 - 联系我们:wmxa8@hotmail.com
打开技术之扣,分享程序人生!