Getting an SPListItem by it's Unique ID

So you have an item's Unique ID from the SPListItem.UniqueId property.  How would you go about getting that item?  I haven't found an easy way to do this through the API without already knowing the ID of the Web and List that it is in.  A way around this is to use the SPSiteDataQuery to search the entire site for that item.  As you will notice, I am running the search inside of the Elevated context to make sure that the item will be returned no matter what permissions the end user has.  You will also notice that I am not passing any ViewFields to the SPSiteDataQuery.  These are not required as WebID, ListID, and (int)(item)ID are returned automatically.  You don't need to loop through all of the DataRows, since there is only one.
     Guid g = {GUID};
     SPSecurity.RunWithElevatedPrivileges(delegate()
     {
         using (SPSite site = new SPSite(SPContext.Current.Site.Url))
         {
             SPSiteDataQuery query = new SPSiteDataQuery();
             query.Webs = "<Webs Scope='SiteCollection' />";
             query.Query = string.Format("<Where><Eq><FieldRef Name="UniqueId" />" +
		+ "<Value Type="Text">{0}</Value></Eq></Where>", Convert.ToString(g));
             query.RowLimit = 1;

             using (DataTable dt = site.RootWeb.GetSiteData(query))
             {
                 foreach (DataRow dr in dt.Rows)
                 {
                     Guid webId = new Guid(Convert.ToString(dr["WebID"]));
                     Guid listId = new Guid(Convert.ToString(dr["ListID"]));
                     using (SPWeb web = site.AllWebs[webId])
                     {
		          SPList list = web.Lists[listId];

		          SPListItem li = null;
		          try
		          {
		              li = list.Items[ g ];
		          }
		          catch { }
		          if (li != null)
		          {
		              // Now you have your item, do what you need to do
		          }
		          list = null;
                     }
                 }
             }
             site.RootWeb.Dispose();
         }
     });

Leave a Reply