Friday 17 April 2015

Setting the content type of a document uploaded to SharePoint Library through CSOM

There might be times when we will have to specify a content type for a file that is programmatically uploaded to a SharePoint library through CSOM. This blog post explains the steps involved in setting the custom content type through CSOM code. In order to set the content type we will be using the ParseAndSetFieldValue method of the list item and set the id of our desired content type to the ContentTypeId property.

The first step is to get the content type if of our content type. This is done by looping through all the content types attached to the library and getting the id of the particular content type.

string serverUrl = "SharePoint Site URL";

     String login = "user name";

            String password = "password";

            string listUrlName = "Library Name";

            string customcontenttypename = "Content Type Name";
 

            ClientContext context = new ClientContext(serverUrl);

           
               var passWord = new SecureString();

                foreach (char c in password.ToCharArray()) passWord.AppendChar(c);

                context.Credentials = new SharePointOnlineCredentials(login, passWord);

           List splist = context.Web.GetList(listUrlName);

             context.Load(splist);

             context.Load(splist.ContentTypes);

             context.ExecuteQuery();

              ContentType ctcustom = null;

foreach (ContentType ct in splist.ContentTypes)

{

if (ct.Name == customcontenttypename)

{
ctcustom = ct;

                               break;
}

}

Then we upload the file to the library

var folder = context.Web.GetFolderByServerRelativeUrl(listUrlName);

context.Load(folder);

var files = folder.Files;

context.Load(files);

       string filepath = @"File Path";

                  
       FileInfo fi = new FileInfo(filepath);

       var fci = new FileCreationInformation

{

Url = fi.Name,

Overwrite = true,

Content = System.IO.File.ReadAllBytes(filepath)
};

 
var file = files.Add(fci);
 
And then we set the content type of our custom content type to ContentTypeId property of the list item attached to the uploaded file

file.ListItemAllFields.ParseAndSetFieldValue("ContentTypeId", ctcustom.Id.ToString());

file.ListItemAllFields.Update();

context.Load(file);  

context.ExecuteQuery();