2012-05-10 115 views
5

我希望能夠從ASP.NET C#中的服務器端提取URL的子目錄的名稱並將其保存爲字符串。例如,可以說我有一個看起來像這樣的URL:從ASP.NET C#中的URL中提取子目錄名稱#

http://www.example.com/directory1/directory2/default.aspx 

我怎麼會從URL中獲得的價值「directory2」?

+1

你可能想成爲一個更確切的一點:你想要的頁面之前的最後一個子目錄?即如果url是'http:// www.abc.com/foo/bar/baz/default.aspx',你想要'baz'? – Filburt

+0

請看我更新的答案。 – jams

回答

12

Uri類有一個名爲segments屬性:

var uri = new Uri("http://www.example.com/directory1/directory2/default.aspx"); 
Request.Url.Segments[2]; //Index of directory2 
+0

你打敗了我。 :) –

+0

+1最好避免字符串拆分/解析時有像Uri一樣方便。 OP沒有具體說明他是否總是想要最後一個subdir--也許你可以在這個案例中選擇一個替代方案。 – Filburt

+0

謝謝!這工作完美! – Kevin

0

可以使用string類的split方法將其分割上/

試試這個,如果你想選擇頁目錄

string words = "http://www.example.com/directory1/directory2/default.aspx"; 
string[] split = words.Split(new Char[] { '/'}); 
string myDir=split[split.Length-2]; // Result will be directory2 

下面是例子來自MSDN。如何使用split方法。

using System; 
public class SplitTest 
{ 
    public static void Main() 
    { 
    string words = "This is a list of words, with: a bit of punctuation" + 
          "\tand a tab character."; 
    string [] split = words.Split(new Char [] {' ', ',', '.', ':', '\t' }); 
    foreach (string s in split) 
    { 
     if (s.Trim() != "") 
      Console.WriteLine(s); 
    } 
    } 
} 
// The example displays the following output to the console: 
//  This 
//  is 
//  a 
//  list 
//  of 
//  words 
//  with 
//  a 
//  bit 
//  of 
//  punctuation 
//  and 
//  a 
//  tab 
//  character 
1

我會用.LastIndexOf( 「/」),並從向後工作。

1

您可以使用System.Uri來提取路徑的段。例如:

public partial class WebForm1 : System.Web.UI.Page 
{ 
    protected void Page_Load(object sender, EventArgs e) 
    { 
     var uri = new System.Uri("http://www.example.com/directory1/directory2/default.aspx"); 
    } 
} 

然後,屬性 「uri.Segments」 是含有這樣4支鏈段的字符串陣列(串[]):[ 「/」, 「directory1中/」, 「directory2 /」,「默認的.aspx「。

1

這是一個sorther代碼:

string url = (new Uri(Request.Url,".")).OriginalString 
相關問題