Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Extract sub-directory name from URL in ASP.NET C#

I want to be able to extract the name of a sub-directory of a URL and save it to a string from the server-side in ASP.NET C#. For example, lets say I have a URL that looks like this:

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

How would I get the value 'directory2' from the URL?

like image 399
Kevin Avatar asked May 10 '12 22:05

Kevin


4 Answers

Uri class has a property called segments:

var uri = new Uri("http://www.example.com/directory1/directory2/default.aspx");
Request.Url.Segments[2]; //Index of directory2
like image 78
Element Avatar answered Oct 29 '22 02:10

Element


This is a sorther code:

string url = (new Uri(Request.Url,".")).OriginalString
like image 24
Oscar Avatar answered Oct 29 '22 03:10

Oscar


I'd use .LastIndexOf("/") and work backwards from that.

like image 21
John Batdorf Avatar answered Oct 29 '22 02:10

John Batdorf


You can use System.Uri to extract the segments of the path. For example:

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");
    }
}

Then the property "uri.Segments" is a string array (string[]) containing 4 segments like this: ["/", "directory1/", "directory2/", "default.aspx"].

like image 35
Mike Panter Avatar answered Oct 29 '22 04:10

Mike Panter