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?
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
This is a sorther code:
string url = (new Uri(Request.Url,".")).OriginalString
I'd use .LastIndexOf("/") and work backwards from that.
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"].
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With