Programmatically Upload document using Client object model – SharePoint 2010


Method 1 -
Here is a simple code for uploading a file without metadata
public Boolean UploadDocument(string fileName, string filePath)
{
ClientContext ctx = new ClientContext(“http://yoursharepointURL”);
Web currentWeb = ctx.Web;
ctx.Load(currentWeb);
ctx.ExecuteQuery();
using (FileStream fs = new FileStream(filePath, FileMode.Open))
{
Microsoft.SharePoint.Client.File.SaveBinaryDirect(ctx, “/Shared Documents/”+ fileName, fs, true);
}
Console.WriteLine(“Uploaded File Successfully”);
}
The above method accepts two parameters one is fileName - name of the file and filePath - the path of the file on your computer or in sharepoint. for e.g. “C:\TestFile.doc”. With this method however, you will not be able to set the metadata for the document ( i couldn’t do it! ) so i used the other method for adding a document and its metadata.
Method 2 –
The below method will upload a file  in sharePoint 2010 document library with the  metadata
public Boolean UploadDocument(String fileName, String filePath, List metaDataList)
{
SP.ClientContext ctx = new SP.ClientContext(“http://yoursharepointURL”);
Web web = ctx.Web;
FileCreationInformation newFile = new FileCreationInformation();
newFile.Content = System.IO.File.ReadAllBytes(@”C:\TestFile.doc”);
newFile.Url = “/” + fileName;
List docs = web.Lists.GetByTitle(“Shared Documents”);
Microsoft.SharePoint.Client.File uploadFile = docs.RootFolder.Files.Add(newFile);
context.Load(uploadFile);
context.ExecuteQuery();
SPClient.ListItem item = uploadFile.ListItemAllFields;
//Set the metadata
string docTitle = string.Empty;
item["Title"] = docTitle ;
item.Update();
context.ExecuteQuery();

Comments

Post a Comment

Popular posts from this blog

IRM and the Object Model

This content database has a schema version which is not supported in this farm

Activate and Deactivate Feature through PowerShell