Parse out last item in URL before last /

Last post 05-08-2008 3:51 PM by Svante. 2 replies.

Sort Posts:

  • Parse out last item in URL before last /

    05-08-2008, 2:45 PM
    • Loading...
    • dba123
    • Joined on 12-13-2003, 12:04 AM
    • Posts 986

     How can I grab the last folder in the URL, before the ending .aspx page?

    example: "/folder1/folder2/..../mypage.aspx

    I want to parse out the last folder name right before the last /
     

    C# Web Developer

    When is Microsoft going to get rid of VB.NET!
  • Re: Parse out last item in URL before last /

    05-08-2008, 2:58 PM
    • Loading...
    • AceCorban
    • Joined on 08-23-2007, 3:43 PM
    • Monterey, CA
    • Posts 374

    This should work for any number of folders even if there is only one

     
    String myUrl = Convert.ToString(Request.Url);
    String directoryPath = myURL.Substring(0, myURL.LastIndexOf("/"));
    //directoryPath will be all folders and parse out the filename: folder1/folder2/folder3
    String lastDirectory = directoryPath.Substring(directoryPath.LastIndexOf("/") + 1);
    //lastDirectory will only be the last foldername 
     
     
    I never lose, some people are just better than me at winning.
  • Re: Parse out last item in URL before last /

    05-08-2008, 3:51 PM
    • Loading...
    • Svante
    • Joined on 02-12-2007, 7:15 AM
    • Stockholm, Sweden
    • Posts 1,581
    • Moderator

     

    string virtualPath = "/folder1/folder2/folderN/mypage.aspx";
    string directory = VirtualPathUtility.GetDirectory(virtualPath);
    string[] folders = directory.Split('/', StringSplitOptions.RemoveEmptyEntires);
    string lastFolder = folders.Length > 0 ? folders[folders.Length - 1] : String.Empty;
    
     
    Svante
    AxCrypt - Free Open Source File Encryption & Online Password Manager - http://www.axantum.com
    [Disclaimer: Code snippets usually uncompiled, beware typos.]
    ______
    Don't forget to click "Mark as Answer" on the post(s) that helped you.
Page 1 of 1 (3 items)