標籤:檔案讀取 解決 方法 pps 無法 不同的 pre logs blog
多線程中的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); } }
HttpContext.Current.Server.MapPath("/") 未將對象設定到對象的執行個體異常。