Search code examples
c#urlslash

Get anything after first slash in URL


I can get my browser url using : string url = HttpContext.Current.Request.Url.AbsoluteUri; But say if I have a url as below :

http://www.test.com/MyDirectory/AnotherDir/testpage.aspx

How would I get the "MyDirectory" part of it, is there a utility in .NET to get this or do I need string manipulation ?

If I do string manipulation and say anything after first instance of "/" then wouldnt it return the slash after http:? It would work if my url was www.test.com/MyDirectory/AnotherDir/testpage.aspx

Can someone please help


Solution

  • Instantiate a Uri instance from your url:

    Uri myUri = new Uri("http://www.test.com/MyDirectory/AnotherDir/testpage.aspx");
    

    You can then get the path segments into a string array using:

    string[] segments = myUri.Segments
    

    Your first "MyDirectory" folder will be at:

    string myFolderName = segments[0];