Take the 2-minute tour ×
SharePoint Stack Exchange is a question and answer site for SharePoint enthusiasts. It's 100% free, no registration required.

I can't seem to upload a file to SharePoint if that file exceeds 2MB or so. I am developing a Silverlight application that is interacting with SharePoint via Managed Client Object Model for Silverlight (Microsoft.SharePoint.Client.Silverlight).

I've read around that the proper file uploading from Client Object Model should be done like so:

Microsoft.SharePoint.Client.File.SaveBinaryDirect(clientContext, 
    targetUrl, fileStream, true);

However, I cannot use the SaveBinaryDirect(...) method because it doesn't exist in the Microsoft.SharePoint.Client.Silverlight assembly.

Right now, I am using this (that's the code that doesn't cope well with +2MB files):

FileCreationInformation fci = new FileCreationInformation();
...
File file = this.list.RootFolder.Files.Add(fci);

Can you help me? Thanks.

share|improve this question
add comment

1 Answer 1

up vote 1 down vote accepted

Here's a way to do it:

Uploading of files is done inside the following method:

public File UploadFile(string fileName, System.IO.Stream fileStream, bool overwrite)
{
    FileCreationInformation fci;
    StringBuilder sb;
    File file;

    fci = new FileCreationInformation();
    fci.Content = this.ReadFully(fileStream);
    fci.Overwrite = overwrite;
    fci.Url = fileName;

    file = this.list.RootFolder.Files.Add(fci);
    return file;
}

The catch is in the ReadFully(System.IO.Stream fileStream) method and setting the byte array size to a fixed value:

private byte[] ReadFully(System.IO.Stream input)
{
    byte[] buffer;
    System.IO.MemoryStream ms;
    int read;

    buffer = new byte[16 * 1024];
    using (ms = new System.IO.MemoryStream())
    {
        while ((read = input.Read(buffer, 0, buffer.Length)) > 0)
        {
            ms.Write(buffer, 0, read);
        }
        return ms.ToArray();
    }
}

The idea was taken from here. It may appear a bit clumsy (there's no guarantee that the file size will not exceed 16 * 1024 bytes), but it works. With a little tweaking, this problem can be overcome as well.

share|improve this answer
1  
why not set the buffer to the size of the file if that is going to be a problem? –  Matt Oct 24 '12 at 15:01
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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