Tutorial :How can I extract the first folder from a URL?


I need to improve the method below.

The idea is to extract the first folder of a URL if it exists. The URLs may be passed with or without a domain, that is to say, http://www.examplecom/es/test/test.aspx, http://example.com/es/test/, or simply /us/xxx/xxx.aspx.

public string ExtractURL(string url)  {      string result = "";      try      {          string[] urlSplitted = url.Split("//".ToCharArray());          //si encontramos /          if (urlSplitted.Length > 0)          {              string strFin = urlSplitted[urlSplitted.GetUpperBound(0) - 1];              //comprobamos que exista algo              if (String.IsNullOrEmpty(strFin))              {                  result = url;              }              else              {                  //devuelvo la url hasta /ES o /EN                  result = url.Substring(0,url.ToLower().IndexOf("/" +strFin.ToLower()));              }          }          else          {              result = url;          }      }      catch      {          result = "";      }      return result;  }  


If you want to solve this with a regular expression (as you tagged your question "regex"), try this:

public string ExtractURL(string url)  {    return Regex.Match(url, "(?<!/)/[^/?#]+").Value;  }  

This regex works on absolute URLs, and on relative URLs that begin with a slash. If it also needs to work on relative URLs without a slash, try this:

public string ExtractURL(string url)  {    Regex.Match(url, @"(\w*:(//[^/?#]+)?/)?(?<folder>[^/?#]+)").Groups["folder"].Value;  }  


Cast to a Uri and then use the Segments property. You'll actually want the second segment because the first is just the leading slash.

public string ExtractURL(string url)  {      Uri webAddress = null;      string firstFolder = null;      if (Uri.TryCreate(url, UriKind.RelativeOrAbsolute, out webAddress))      {          if (!webAddress.IsAbsoluteUri)          {              webAddress = new Uri(Request.Url, url);          }          if (webAddress.Segments.Length >= 2)          {              firstFolder = webAddress.Segments[1];          }      }      return firstFolder;  }  


Consider using System.Uri class to pre-parse the Uri and extract the relative path with LocalPath property. Then use String.split().


public string ExtractURL(string URL)      {          string result = "";          try          {              httpindex = URL.ToLower().IndexOf("http://");              if (httpindex > 0)              {                  URL = URL.Substring(0, 6);              }              URL = URL.ToLower().TrimStart("http://".ToCharArray());              string[] urlArray = URL.Split('/');              if (urlArray.Length > 1)              {                      result = urlArray[1];              }          }          catch          {              result = "";          }          return result;      }  

That should do what you want I think


I agree with Sergii Volchkov and I think using System.Uri is the right way to go but instead of using string.split you may want to use Path.GetParentDirectory() on the local path.

Note:If u also have question or solution just comment us below or mail us on toontricks1994@gmail.com
Next Post »