2012-05-10 116 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 
相关问题