Extract subdirectory name from URL in ASP.NET C #

I want to get the name of a subdirectory of a URL and save it in a line from the server side in ASP.NET C #. For example, let's say I have a URL that looks like this:

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

How do I get the value "directory2" from a URL?

+5
source share
5 answers

The Uri class has the segments property :

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

I would use .LastIndexOf ("/") and step back from it.

+1
source

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" ].

+1

:

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

split string, /

,

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

Here is an example from MSDN. How to use the method 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
0
source

All Articles