HttpContext.Current.Server.MapPath("/") 未將對象設定到對象的執行個體異常。

來源:互聯網
上載者:User

標籤:檔案讀取   解決   方法   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("/") 未將對象設定到對象的執行個體異常。

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.