在ASP.NET C#中从URL中提取子目录名称

5

我希望能够从ASP.NET C#服务器端提取URL的子目录名称并将其保存到字符串中。例如,假设我有一个URL看起来像这样:

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

我怎样从URL中获取值“directory2”?


1
你可能需要更加精确:你想要页面之前的最后一个子目录吗?例如,如果URL是http://www.abc.com/foo/bar/baz/default.aspx,你想要的是baz - Filburt
5个回答

12

Uri类有一个名为segments的属性:

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

最好避免字符串拆分/解析,如果有像Uri这样方便的东西。OP没有指定他是否总是想要最后一个子目录 - 也许你可以为这种情况提供另一种选择。 - Filburt

2

下面是一个排序代码:

string url = (new Uri(Request.Url,".")).OriginalString

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"是一个字符串数组(string []),包含4个段,如下所示: ["/", "directory1 /", "directory2 /", "default.aspx"]。


0
你可以使用字符串类的 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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接