Pregunta

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

¿Fue útil?

Solución

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];

Otros consejos

You can get this by PathAndQuery property of Url

var path = HttpContext.Current.Request.Url.PathAndQuery;

it will return /MyDirectory/AnotherDir/testpage.aspx

 Uri uriAddr = new Uri("http://www.test.com/MyDirectory/AnotherDir/testpage.aspx");
 var firstSegment= uriAddress.Segments.Where(seg => seg != "/").First();
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top