【问题标题】:Extract sub-directory name from URL in ASP.NET C#从 ASP.NET C# 中的 URL 中提取子目录名称
【发布时间】:2012-05-19 13:17:18
【问题描述】:

我希望能够从 ASP.NET C# 中的服务器端提取 URL 子目录的名称并将其保存为字符串。例如,假设我有一个如下所示的 URL:

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

如何从 URL 中获取值“directory2”?

【问题讨论】:

  • 您可能想要更精确一点:您想要页面之前的最后一个子目录?即如果 url 是 http://www.abc.com/foo/bar/baz/default.aspx 你想要baz?
  • 请看我更新的答案。

标签: c# asp.net string url path


【解决方案1】:

您可以使用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

【讨论】:

    【解决方案2】:

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

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

    【讨论】:

    • +1 最好避免在有像 Uri 这样方便的东西时进行字符串拆分/解析。 OP 没有指定他是否总是想要最后一个子目录 - 也许你可以为这种情况提供一个替代方案。
    【解决方案3】:

    我会使用 .LastIndexOf("/") 并从那里向后工作。

    【讨论】:

      【解决方案4】:

      您可以使用 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”]。

      【讨论】:

        【解决方案5】:

        这是一个分拣机代码:

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

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2011-12-11
          • 1970-01-01
          • 2020-01-31
          • 2019-12-17
          • 2020-05-11
          • 1970-01-01
          相关资源
          最近更新 更多