Get SPListItem from URL

Hi Guys! Today I decided to post a snippet of code that I find very useful.

This code retrieves a SPListItem from an absolute URL. The item can be associated to a document or not and the URL can be a display form or not. The main interest of such a code is to retrieve the item associated to an URL returned by the search engine for example.

The good thing is that it works with documents that does not have a IFilter associated. JPEG files for example are not fully indexed by the search engine. The content of the file is not read, only metadata are indexed unless you installed a IFilter supporting JPEG files. The side effect is the url returned by the search engine : this is the display form URL of the file, not the URL of the file itself. So this code handle this case and can be used in such a context.

public static class Utility
    {
        private static readonly Regex ItemIdQsRegex = new Regex(@"(\?|\&)ID=(?<ID>[0-9]+)", RegexOptions.Compiled & RegexOptions.IgnoreCase);

        /// <summary>
        /// Gets the SPListItem that is associated to the specified absolute URL.
        /// The item can be : an item, a page, a document, a document in a folder.
        /// </summary>
        /// <returns>The SPListItem associated to the URL.</returns>
        public static SPListItem GetItemByUrl(string absoluteUrl)
        {
            using (SPSite cSite = new SPSite(absoluteUrl))
            {
                using (SPWeb cWeb = cSite.OpenWeb())
                {
                    SPFile file = cWeb.GetFile(absoluteUrl);
                    SPListItem item = file.Item;
                    if (item != null)
                        return item;
                    else
                    {
                        Uri webUri = new Uri(cWeb.Url);
                        Uri itemUri = new Uri(absoluteUrl);
                        string siteRelativeListUrl = GetSiteRelativeListUrl(webUri, itemUri);
                        if (!string.IsNullOrEmpty(siteRelativeListUrl))
                        {
                            SPList list = cWeb.GetList(cWeb.ServerRelativeUrl + siteRelativeListUrl);

                            Match idMatch = ItemIdQsRegex.Match(absoluteUrl);
                            if (idMatch.Groups["ID"].Success)
                            {
                                int itemId;
                                if (int.TryParse(idMatch.Groups["ID"].Value, out itemId))
                                {
                                    return list.GetItemById(itemId);
                                }
                            }
                            throw new Exception("Cannot retrieve item ID.");
                        }
                        throw new Exception("Cannot find the list.");
                    }
                }
            }
        }

        /// <summary>
        /// Substracts the webUri of the itemUri to get the site-relative URL of the List associated to the specified item URL.
        /// </summary>
        /// <param name="webUri">The absolute URL of the site which contains the Item</param>
        /// <param name="itemUri">The absolute URL of the item</param>
        /// <returns></returns>
        public static string GetSiteRelativeListUrl(Uri webUri, Uri itemUri)
        {
            string webRelativeUrl = webUri.MakeRelativeUri(itemUri).ToString();
            string siteRelativeListUrl = webRelativeUrl.Substring(webRelativeUrl.IndexOf('/'));

            int startIdx = 1;
            int listsIdx = siteRelativeListUrl.IndexOf("/Lists", StringComparison.InvariantCultureIgnoreCase);
            if (listsIdx >= 0) startIdx += listsIdx + "/Lists".Length;

            int endIdx = siteRelativeListUrl.IndexOf('/', startIdx);
            siteRelativeListUrl = siteRelativeListUrl.Substring(0, endIdx);

            return siteRelativeListUrl;
        }
    }

Add comment

biuquote
  • Comment
  • Preview
Loading

About me

After sudying at SUPINFO Indian Ocean and SUPINFO Montreal I am now Analyst Programmer at Ivanhoe Cambridge. 

Month List