How to: Get the Item Id from a document URL
Posted
Monday, November 24, 2008 3:16 PM
by
CoreyRoth
Since I deal with Enterprise Search a lot, I often want to do things in SharePoint given nothing but a URL. Unfortunately, there isn't an API call (that I know that can take a URL can conveniently spit out an Item Id). You can probably use a CAML query, but you would have to know which site collection to start with. So how do we get the id? It takes a number of steps, but it is pretty simple. We first start by opening an SPSite object given the full URL to the item.
using (SPSite siteCollection = new SPSite(url))
{
using (SPWeb site = siteCollection.OpenWeb())
This assumes that the code is executing somewhere where opening an SPSite object for that URL is valid. After that we open a SPWeb object which gives us an object representing the site that contains the document. Next it is a matter of splitting the URL to get a file and folder URL.
// site url
string siteUrl = site.Url;
// get the position of the last slash so that the string can be split
int lastSlashPosition = url.LastIndexOf('/');
// folder url
string folderUrl = url.Substring(0, lastSlashPosition);
// fileUrl
string fileUrl = url.Substring(lastSlashPosition + 1);
We do this by using LastIndexOf('/) (which of course assumes that the URL contains slashes). At this point it is easy to get a reference to the file object representing the document.
// get file object
SPFile file = folder.Files[fileUrl];
This gives us a reference to the file which means we can get a reference to the item and then its Id. Conversely if you are interested in the SPFolder object, you can just use.
// get folder object
SPFolder folder = site.GetFolder(folderUrl);
We will now get the SPListItem object which will give us its Id.
// get the list item
SPListItem item = file.Item;
// get the list item id
int itemId = item.ID;
// get the uniqueId for the list item
Guid uniqueId = item.UniqueId;
Above, I have code to return the internal list item id as well as the unique id. There are a few steps involved, but it seems to work pretty well. You will of course want to add proper error handling and check for nulls along the way, but this should be a good start. This is the same way I get the information I need for the Document Link Handler for Enterprise Search.