Getting Document Library name from URL string

Here's what was happening. I needed to extract the document library name from an intranet URL that a user enters. So they would enter something like this as the URL: http://intranet/site/subsite/DocLib1/Forms/AllItems.aspx and from there I need to extract DocLib1 as SPDocumentLibrary. Problem here is that no matter the depth, I still need to find the document library name and manipulate it as SPDocumentLibrary.

I'm not sure if my way is the best way to do it, but it did work...

            SPSite site = new SPSite(strURL);
            SPWeb web = site.OpenWeb();

            string[] explode = strURL.Replace(web.Url, "").Split(new char[] { '/' });
            string splitURL = explode[1];

            string docLibName = SPEncode.UrlDecodeAsUrl(splitURL); // (this is also the list name with the location we're after)
            SPList thisDocLib = web.Lists[docLibName];

If you do a check for thisDocLib.BaseType, you will find it's of the type DocumentLibrary.

Now, how would it work if it were the folder that we were after instead of a document library?

Leave a Comment

Please note: Comment moderation is enabled and may delay your comment. There is no need to resubmit your comment.