Sending large data with CSOM

As a follow up to my recent post showing how to create or overwrite a document using the CSOM, I’m now going to show how to upload a file containing large amounts of data. To see the original post, click here.

Previously, when saving the binary data, I demonstrated the functionality with the following code:

public void SaveFile(Microsoft.SharePoint.Client.ClientContext context, string folderRelativeUrl, string relativeItemUrl, byte[] fileData)
{
    var fci = new FileCreationInformation
    {
        Url = relativeItemUrl,
        Content = fileData,
        Overwrite = true
    };
 
    Microsoft.SharePoint.Client.Folder folder = context.Web.GetFolderByServerRelativeUrl(folderRelativeUrl);
    Microsoft.SharePoint.Client.FileCollection files = folder.Files;
    Microsoft.SharePoint.Client.File file = files.Add(fci);
 
    context.Load(files);
    context.Load(file);
    context.ExecuteQuery();
}

The above code, by default, will be restricts to transferring files that are no more than 2091752 bytes in size, or 2MB.

To get around this, we’ll set the content for the FileCreationInformation object using the ContentStream property instead of the Content property.

As it sounds, this property accepts a Stream object instead of a byte array. The updated code looks like:

public void SaveFile(Microsoft.SharePoint.Client.ClientContext context, string folderRelativeUrl, string relativeItemUrl, byte[] fileData)
{
    using (System.IO.Stream stream = new System.IO.MemoryStream(fileData))
    {
        var fci = new FileCreationInformation
        {
            Url = relativeItemUrl,
            ContentStream = stream,
            Overwrite = true
        };
 
        Microsoft.SharePoint.Client.Folder folder = context.Web.GetFolderByServerRelativeUrl(folderRelativeUrl);
        Microsoft.SharePoint.Client.FileCollection files = folder.Files;
        Microsoft.SharePoint.Client.File file = files.Add(fci);
 
        context.Load(files);
        context.Load(file);
        context.ExecuteQuery();
    }
}

This will result in the file creation or upload streaming the data instead of attempting to do it all in the one pass, allowing larger sized files to be uploaded.

Hope this helps!

5 comments

  1. Ira says:

    Wow!

    This is the tip I have been searching for.

    Thanks.

  2. Christoph says:

    Worked perfectly !!!! Thanks very much !

  3. Andy M says:

    ContentStream is new in SharePoint 2013 and does not exist in SharePoint 2010 🙁

  4. nitu bansal says:

    thanks a lot! great solution

Leave a Reply

Your email address will not be published. Required fields are marked *

Solve the maths problem shown below before posting: *

Follow

Get every new post delivered to your Inbox

Join other followers: