Programmatically Upload Document using Client Object Model in SharePoint

  1. public Boolean UploadDocument(String fileName, String filePath, List metaDataList)   
  2. {  
  3.     SP.ClientContext ctx = new SP.ClientContext(“http: //yoursharepointURL”);  
  4.     Web web = ctx.Web;  
  5.     FileCreationInformation newFile = new FileCreationInformation();  
  6.     newFile.Content = System.IO.File.ReadAllBytes(@”C: \TestFile.doc”);  
  7.     newFile.Url = “ / ” + fileName;  
  8.     List docs = web.Lists.GetByTitle(“Shared Documents”);  
  9.     Microsoft.SharePoint.Client.File uploadFile = docs.RootFolder.Files.Add(newFile);  
  10.     context.Load(uploadFile);  
  11.     context.ExecuteQuery();  
  12.     SPClient.ListItem item = uploadFile.ListItemAllFields;  
  13.     //Set the metadata  
  14.     string docTitle = string.Empty;  
  15.     item[“Title”] = docTitle;  
  16.     item.Update();  
  17.     context.ExecuteQuery();  
  18. }