.net – How to get a Document’s URL from the Sharepoint CSOM ListItem class

csomnetsharepoint

I need to query a Sharepoint 2013 Document Library and retrieve all documents where a field value in the list equals a certain value. I am using the Sharepoint 2013 CSOM client for this (Microsoft.SharePoint.Client).

I can successfully retrieve all of the ListItem fields except the URL for the document with the following code:

ClientContext spContext = new ClientContext(spDocLibSite);
List cjList = spContext.Web.Lists.GetByTitle(spDocLibTitle);

CamlQuery listItemQuery = CamlQuery.CreateAllItemsQuery(100);
listItemQuery.ViewXml = "ViewXml that limits ListItems returned based on a field val";
ListItemCollection docItems = cjList.GetItems(listItemQuery);

spContext.Load(docItems);
spContext.ExecuteQuery();

foreach (ListItem listItem in docItems)
{
  Console.WriteLine(listItem["Title"]);   //  Works correctly with all fields except URL

  listItem.File.Name or Title;  // Does not work, get field not initialized error
}

The File property doesn't seem to have any data about the Document, I get errors when I try to access its properties.

I didn't set up this document library, but it appears to be standard with a single document for each list item and about a dozen fields with various information about the document. If I look at the field list of the Library/List, the Document/URL isn't even listed as a field. Can I somehow get the URL of the document from the ListItem class that I'm already retrieving? Thanks.

Best Answer

After more research I found the FileRef field/column that has a relative URL that I can build into a full URL:

string spDocUrl = spSiteUri.Scheme + "://" + spSiteUri.Host + listItem["FileRef"];    
Related Topic