2013-04-18 112 views
2

我有一個導航欄,裏面有一個bulletedList。我這樣做的目的是能夠根據當前頁面在網站上的位置來改變類別。我有可以找到當前文件名的代碼,但我希望能夠檢索當前文件所在的文件夾的名稱。我該怎麼做呢?獲取當前頁面的文件夾名稱ASP.NET C#

protected void Page_Load(object sender, EventArgs e) 
{ 
    string[] file = Request.CurrentExecutionFilePath.Split('/'); 
    string fileName = file[file.Length-1]; 

    if (fileName == "Dashboard.aspx") 
    { 
     MainNavList.Items.FindByText("Dashboard").Attributes.Add("class", "active"); 
    } 
} 
+2

字符串文件名=文件[file.Length - 2]。會給你的文件夾之前的文件夾?不知道如果您爲根頁面中的頁面執行此操作會發生什麼情況。可能要測試如果file.Length> 1 – Yeronimo

+0

**好!**謝謝!您的解決方案非常棒! – user2059225

回答

1

謝謝Yeronimo!我所做的只是將-1改爲-2,並放入名爲「Dashboard」的文件夾中。這是對我工作:

protected void Page_Load(object sender, EventArgs e) 
{ 
    string[] file = Request.CurrentExecutionFilePath.Split('/'); 
    string fileName = file[file.Length-2]; 

    if (fileName == "Dashboard") 
    { 
     MainNavList.Items.FindByText("Dashboard").Attributes.Add("class", "active"); 
    } 

}

2

隨着HttpContext.Current.Request.Url.AbsolutePath你可以得到當前的URL路徑。

作爲例子,如果我訪問的頁面是:

http://www.website.com/Directory1/Directory2/Page.aspx

然後,它輸出的字符串,你可以使用split()

/Directory1/Directory2/Page.aspx

0

嘗試使用Request.MapPathRequest.PhysicalPath到獲取ASPX文件在磁盤上的位置。