C#取得Web程序及WinForm程序的根目錄路徑的方法

取得控制檯應用程序的根目錄方法
方法一、Environment.CurrentDirectory 取得或設置當前工做目錄的完整限定路徑
方法二、AppDomain.CurrentDomain.BaseDirectory 獲取基目錄,它由程序集衝突解決程序用來探測程序集web

 

 

取得WinForm應用程序的根目錄方法
一、Environment.CurrentDirectory.ToString();//獲取或設置當前工做目錄的徹底限定路徑
二、Application.StartupPath.ToString();//獲取啓動了應用程序的可執行文件的路徑,不包括可執行文件的名稱
三、Directory.GetCurrentDirectory();//獲取應用程序的當前工做目錄
四、AppDomain.CurrentDomain.BaseDirectory;//獲取基目錄,它由程序集衝突解決程序用來探測程序集
五、AppDomain.CurrentDomain.SetupInformation.ApplicationBase;//獲取或設置包含該應用程序的目錄的名稱數據庫

 

 

取得web應用程序的根目錄方法網站

1.HttpContext.Current.Server.MapPath("~/configs/ChannelUsers.xml")orm

 

HttpContext.Current
返回當前請求的 HttpContext 對象。如此咱們就能夠直接訪問Request、Response、Session、Application等對象,和Page中訪問等同。
咱們無需再將Page用參數的方式傳遞到咱們的類庫對象中。xml

HttpContext.Current.Session["name"] = "豬八戒";
string name = HttpContext.Current.Request.Param["name"];
HttpContext.Current.Response.Write("豬八戒好吃懶作!");對象

 

獲取網站根目錄的方法有幾種如:string

Server.MapPath(Request.ServerVariables["PATH_INFO"])
Server.MapPath("/")
Server.MapPath("")
Server.MapPath(".")
Server.MapPath("../")
Server.MapPath("..") 
Page.Request.ApplicationPath
運行結果:
C:\Inetpub\wwwroot\EnglishClub\manage\WebForm1.aspx
C:\Inetpub\wwwroot\
C:\Inetpub\wwwroot\EnglishClub\manage
C:\Inetpub\wwwroot\EnglishClub\manage
C:\Inetpub\wwwroot\EnglishClub\
C:\Inetpub\wwwroot\EnglishClubit

以上的方法能夠在.aspx中訪問,可是若是你在。cs文件就不能用。io

 

HttpContext.Current.Server.MapPath();
System.Web.HttpContext.Current.Request.PhysicalApplicationPath   
form

在.cs文件中能夠用。

可是HttpContext.Current.Server.MapPath();這個獲取的是文件的路徑而不是根目錄。

只有System.Web.HttpContext.Current.Request.PhysicalApplicationPath    這個纔是獲取的根目錄,在寫獲取數據庫路徑是應該用這個,其餘的都有問題。

相關文章
相關標籤/搜索