System.Web.HttpContext.Current.Server.MapPath ("/") in multi-threading
Server.MapPath in multi-threading will fail ...
Find several solutions on the web, now organized as follows:
The first type:
System.Web.HttpContext.Current.Server.MapPath ("/") is commonly used to represent the root of a Web site, but in multi-threading, an instance of an object that is not set to object references occurs. So do not distribute in different classes, as far as possible in a global location, and then other classes share this, after all, the site directory is not changed, you can use a static variable to represent.
the method: Not very good;
The second type:
It would be nice to have a directory of Web apps if needed. Suppose the Web root directory is: c:\www, and DB is placed under the WWW directory. System.AppDomain.CurrentDomain.BaseDirectory.ToString () + configurationmanager.appsettings["DbPath"] it's OK.
I found a way, that's it.
This is a way to read from the configuration file in the path download configuration file and feel OK.
The third type:
The use of httpcontext.current,httpcontext.current in multi-threaded is given null. 20150703 explains why the current request context is NULL, because in multithreaded situations the current thread may not be the HTTP request processing thread, and no request has occurred, so it is not possible to obtain a HttpContext that is null.
So use:
Public Static stringMapPath (stringstrpath) { if(HttpContext.Current! =NULL) { returnHttpContext.Current.Server.MapPath (strpath);//have an HTTP request } Else //non-web program reference{strpath= Strpath.replace ("/","\\"); if(Strpath.startswith ("\\")) { //strpath = strpath.substring (strpath.indexof (' \ \ ', 1)). TrimStart (' \ \ '); strpath = Strpath.trimstart (' \ \ '); } returnSystem.IO.Path.Combine (AppDomain.CurrentDomain.BaseDirectory, strpath); } }
HttpContext.Current.Server.MapPath ("/") did not set the object to an instance exception for the object.