Uploading files using Client Object Model in SharePoint 2010

There are 2 ways to upload files to SharePoint 2010 document libraries using managed client object model.

The first method uses a client library batch mechanism.  It will encode the binary using BASE64 encoding, which could increase the message size by one third.  There might be problems if this isn’t configured correctly.  An example of this code is below:

    1: ClientContext context = new ClientContext("http://spdevinwin");
    3: Web web = context.Web;
    5: FileCreationInformation newFile = new FileCreationInformation();
    6: newFile.Content = System.IO.File.ReadAllBytes(@"C:\Work\Files\17580_FAST2010_S05_Administration.pptx");
    7: newFile.Url = "17580_FAST2010_S05_Administration 4MB file uploaded via client OM.pptx";
    9: List docs = web.Lists.GetByTitle("Documents");
   10: Microsoft.SharePoint.Client.File uploadFile = docs.RootFolder.Files.Add(newFile);
   11: context.Load(uploadFile);
   12: context.ExecuteQuery();
   13: Console.WriteLine("done");

The above code might fail throwing a (400) Bad Request error depending on the file size.  The following code is used to set a higher limit to the upload size.  Note: This is not the same as the max. file size upload limit option available in the web application settings.

    1: SPWebService ws = SPWebService.ContentService;
    2: SPClientRequestServiceSettings clientSettings = ws.ClientRequestServiceSettings;
    3: clientSettings.MaxReceivedMessageSize = 10485760;
    4: ws.Update();
    5: Console.WriteLine(clientSettings.MaxReceivedMessageSize);

The above code sets the message batch size to 10MB so that larger files can be uploaded using managed client object model.

The second methods uses HTTP DAV and sends raw binary across the wire and does not increase the message size.  It is also the preferred upload method when using managed client object model.  Here’s a sample:

    1: ClientContext context = new ClientContext("http://spdevinwin");
    2: using (FileStream fs = new FileStream(@"C:\Work\Files\17580_FAST2010_S03_Arch.pptx", FileMode.Open))
    3: {
    4:     Microsoft.SharePoint.Client.File.SaveBinaryDirect(context, "/documents/17580_FAST2010_S03_Arch from client OM.pptx", fs, true);
    5: }

Hope this helps!  Stay tuned for most posts on managed client object model.