1

I am trying to use the Client Object Model in SharePoint to upload a document to a specific library. Right now I have it saving the document but I can't figure out how to specify the content type before uploading.

using(var context = new ClientContext("http://mysharepoint/sites/Demo"))
{
    Web currentWeb = context.Web;

    context.Load(currentWeb, web => web.Url);
    context.ExecuteQuery();

    List documentList = context.Web.Lists.GetByTitle("Public Documents");

    context.Load(documentList, list => list.EntityTypeName);
    context.ExecuteQuery();

   var newFile = new FileCreationInformation()
   {
       Content = ...,
       Overwrite = true,
       Url = "myfile.docx"
   };

   var uploadFile = documentList.RootFolder.Files.Add(newFile);

   // how to set the content type?
   context.Load(uploadFile);
   context.ExecuteQuery();
}

I'm not positive this is the correct way to upload the document so if there is something else wrong please point it out.

Additional question. I am doing this in an Office Add-In project and would like to show the Document Information Panel so they can edit the metadata. Is it possible to do this before uploading the file or would I need to do it after the file is uploaded?

2

The example demonstrates how to specify list item properties (Content Type in this case) while uploading the file:

var targetList = context.Web.Lists.GetByTitle(listTitle);
var fileInfo = new FileCreationInformation()
    {
      Content = fileContent,
      Overwrite = true,
      Url = fileUrl
    };

var uploadFile = targetList.RootFolder.Files.Add(fileInfo);
var listItem = uploadFile.ListItemAllFields; //get associated list item
listItem["ContentTypeId"] = ctId;  //set content type
listItem.Update();

context.Load(uploadFile);
context.ExecuteQuery();  

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.