多线程中的System.Web.HttpContext.Current.Server.MapPath("/")
多线程中(包括在async 中),Server.MapPath会失效。。。 获取为Null
网上找到几种解决方法,现在整理如下:
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的.
解释下为什么当前请求上下文会为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);
回答的也多数都是:引用System.Web,不要用HttpContext.Current.Application应该用System.Web.HttpContext.Current.Application,后来在网上看到一篇关于System.Runtime.Remoting.Messaging.CallContext这个类的详细介绍才知道,原来HttpContext.Current是基于System.Runtime.Remoting.Messaging.CallContext这个类,子线程和异步线程都无法访问到主线程在CallContext中保存的数据。所以在异步执行的过程会就会出现HttpCo
解决代码如下:
XmlDocument xml = new XmlDocument(); //加载xml文件 try { if (HttpContext.Current !...
老是忘记Server.MapPath的使用方法了,下面记录一下,以备后用:总注:Server.MapPath获得的路径都是服务器上的物理路径,也就是常说的绝对路径1、Server.MapPath("/")注:获得应用程序根目录所在的位置,如 C:\Inetpub\wwwroot\。2、Server.MapPath("./")注:获得所在页面的当前目录,等价于Server.MapPath("")。3...