SUN SUN - 3 months ago 18
C# Question

Get first part from url(first root directory value only) in c#

I have this url (www.site.com/folder1/sub-folder)

Now I just want to get only folder1 from this url. How can I do that? I'm getting Last root url from below code but I want only first root url.

string s = Page.Request.Url.AbsolutePath;
s = s.Substring(s.LastIndexOf("/")+1);


Pls help me to get only first directory value.

Answer

You can use Split() method twice like

string str = "www.site.com/folder1/sub-folder";
string folder = (str.Split('/')[1]).Split('/')[0];
Comments