SharePoint Tips

Thursday, November 16, 2017

CSOM - Get Document metadata from SharePoint Library - C#

public ListItemCollection GetDocumentMetaData(ClientContext clientContext, string libraryName)
{
ListItemCollection items = null;
try
{
 // true to enable 100-Continue behavior.The default value is true.
ServicePointManager.Expect100Continue = true;
  // Default .Net SecurityProtocol. To disable SSL fallback
ServicePointManager.SecurityProtocol = SecurityProtocolType.Ssl3;

List library = clientContext.Web.Lists.GetByTitle(libraryName);

clientContext.Load(library);
clientContext.Load(library.RootFolder);
clientContext.Load(library.RootFolder.Folders);
clientContext.Load(library.RootFolder.Files);
clientContext.ExecuteQuery();

if (library != null && library.ItemCount > 0)
{
// Add all your CAML query conditions in below variable
List<string> conditions = new List<string>();
CamlQuery camlQuery = new CamlQuery();
string serverRelativeUrl = library.RootFolder.ServerRelativeUrl + "/Folder Name";
camlQuery.FolderServerRelativeUrl = serverRelativeUrl;
string viewXml = @"<View Scope='Recursive'>
<Query><Where>" + conditions +
   @"</Where></Query>                           
</View>";
camlQuery.ViewXml = viewXml;

items = library.GetItems(camlQuery);

clientContext.Load(items, listItems => listItems.Include
(item => item.FileSystemObjectType,
item => item.ContentType,
item => item.DisplayName,
item => item["FileLeafRef"],
item => item["Modified"],
item => item["Title"],
item => item["FileRef"],
item => item["CustomField1"],
item => item["CustomField2"],
item => item["Created"]));
clientContext.ExecuteQuery();

}

}
catch (Exception exec)
{
logger.WriteEventLog("Please contact admin : " + exec.Message);
throw exec;
}
int count = items.Count;
return items;
}

No comments:

Post a Comment