(越辰家政軟件部整理)幾種方法如下: 非Web程序
1.AppDomain.CurrentDomain.BaseDirectory //瀏覽器安裝路徑
2.Environment.CurrentDirectory
3.HttpRuntime.BinDirectory
The path to the current application's/bin directory.
Web程序
HttpCurrent.Context.Server.Mappath();
---------------------------------------------------------------
HttpContext.Current
返回當(dāng)前請(qǐng)求的 HttpContext 對(duì)象。如此我們就可以直接訪問Request、Response、Session、Application等對(duì)象,和Page中訪問等同。 我們無需再將Page用參數(shù)的方式傳遞到我們的類庫對(duì)象中。
HttpContext.Current.Session["name"] = "豬八戒"; string name = HttpContext.Current.Request.Param["name"]; HttpContext.Current.Response.Write("豬八戒好吃懶做!");
HttpRuntime
為當(dāng)前應(yīng)用程序提供一組 ASP.NET 運(yùn)行時(shí)服務(wù)。我們可以通過這個(gè)類獲得當(dāng)前ASP.NET工程的一些信息。
HttpRuntime.AppDomainAppVirtualPath : 項(xiàng)目虛擬路徑 HttpRuntime.AppDomainAppPath : 項(xiàng)目物理路徑 HttpRuntime.BinDirectory : BIN目錄物理路徑 HttpRuntime.ClrInstallDirectory : CLR安裝路徑(可以用來獲取CLR版本號(hào))
Response.Write(string.Format("AppDomainAppId: {0}<br>", HttpRuntime.AppDomainAppId)); Response.Write(string.Format("AppDomainAppPath: {0}<br>", HttpRuntime.AppDomainAppPath)); Response.Write(string.Format("AppDomainAppVirtualPath: {0}<br>", HttpRuntime.AppDomainAppVirtualPath)); Response.Write(string.Format("AppDomainId: {0}<br>", HttpRuntime.AppDomainId)); Response.Write(string.Format("AspInstallDirectory: {0}<br>", HttpRuntime.AspInstallDirectory)); Response.Write(string.Format("BinDirectory: {0}<br>", HttpRuntime.BinDirectory)); Response.Write(string.Format("ClrInstallDirectory: {0}<br>", HttpRuntime.ClrInstallDirectory)); Response.Write(string.Format("CodegenDir: {0}<br>", HttpRuntime.CodegenDir)); Response.Write(string.Format("IsOnUNCShare: {0}<br>", HttpRuntime.IsOnUNCShare.ToString())); Response.Write(string.Format("MachineConfigurationDirectory: {0}<br>", HttpRuntime.MachineConfigurationDirectory));
輸出: AppDomainAppId: /LM/W3SVC/1/Root/Learn.Test.Web AppDomainAppPath: D:\System\My Documents\Visual Studio Projects\Learn.Test\Learn.Test.Web\ AppDomainAppVirtualPath: /Learn.Test.Web AppDomainId: /LM/W3SVC/1/Root/Learn.Test.Web-9-127652564154400560 AspInstallDirectory: C:\WINDOWS\Microsoft.NET\Framework\v1.1.4322 BinDirectory: D:\System\My Documents\Visual Studio Projects\Learn.Test\Learn.Test.Web\bin\ ClrInstallDirectory: c:\windows\microsoft.net\framework\v1.1.4322 CodegenDir: C:\WINDOWS\Microsoft.NET\Framework\v1.1.4322\Temporary ASP.NET Files\learn.test.web\41680132\7c880883 IsOnUNCShare: False MachineConfigurationDirectory: c:\windows\microsoft.net\framework\v1.1.4322\Config
HostingEnvironment
string siteName = HostingEnvironment.SiteName; string appPath = HostingEnvironment.ApplicationVirtualPath; string phyPath = HostingEnvironment.ApplicationPhysicalPath; string adminPath = HostingEnvironment.MapPath("~/Admin");
ApplicationManager.GetApplicationManager().ShutdownApplication(HostingEnvironment.ApplicationID);
靈活運(yùn)用技巧:
當(dāng)使用非WEB程序或使用異步調(diào)用時(shí),想要取得根目錄下的某目錄可以使用如下代碼:
HttpRuntime.BinDirectory + "../目錄名";
|