Question

I'm missing something that must be so simple that it's not even worth asking... but I have an object ID (GUID)... How do I figure out the document it points to?

For example I have a GUID of 137DA01F-9AFD-5d9d-80C7-02AF85C822A8 and need to know what file/url it points to.

Was it helpful?

Solution

If you know the SPWeb but not the document library, you can use SPWeb.GetFile:

SPFile file = web.GetFile(guid);

OTHER TIPS

Simpliest case

Consider you know that document is stored in standard "Shared Documents" library from the Team Site Template, you should use this code:

var library = web.GetListFromUrl("http://site/Shared%20Documents/Forms/AllItems.aspx");
var file = library.Items[new Guid("137DA01F-9AFD-5d9d-80C7-02AF85C822A8")].File;
// file.Url - site-relative url of the file
// file.OpenBinary() - get file contents (returns byte[])

MSDN references:

  1. SPListItemCollection.Item(Guid)
  2. SPFile.OpenBinary (with sample code)

Library with folders

In more complex case, when you have some folders in your document library, probably the best way will be to use the CAML query for this purpose:

var query = new SPQuery();
query.ViewAttributes = "Scope=\"Recursive\"";
query.View = 
@"<Where>
  <Eq>
    <FieldRef Name=\"UniqueId\">
    <Value Type='Text'>137DA01F-9AFD-5d9d-80C7-02AF85C822A8</Value>
  </Eq>
</Where>";
var items = library.GetItems(query);

Library unknown

If you even don't know in which library the file is stored, you should go through all the libraries of the site:

 foreach (var library in web.Lists)
 {
     if (!library.Hidden && library is SPDocumentLibrary)
     {
         // ... try to get the file and so on
     }
 }

Document IDs

Also, you should surely read about Document IDs feature, which allows you to reference a document from anywhere:

http://blogs.technet.com/b/blairb/archive/2009/10/20/new-document-id-feature-in-sharepoint-2010.aspx

Note: Your Guid, of course, is not a document ID.

There's the SPList.GetItemByUniqueId function, but if you don't know which list to search you're out of luck.

If you're using SharePoint 2010, look at the Document ID functionality (which attaches a unique ID to a list item and then uses Search to find the item). Depending upon your requirements, you might consider implementing "FindItemInSiteCollectionByUniqueId" using a similar approach to Document IDs, making the guid a Managed Property and conducting a search via code.

Licensed under: CC-BY-SA with attribution
Not affiliated with sharepoint.stackexchange
scroll top