Sharepoint allows uploading files in document libraries using the client object model. But if the file is larger than 2MB, it’s not that simple!
In fact, to upload a file we have two different options, RootFolder.Files.Add and File.SaveBinaryDirect. The first one seems simple, so I tried it and it works fine for files less than 2MB in both 2010 and 2013. But for files larger than 2MB, it raises error. The error and the solution for both versions of share point is here:
Sharepoint 2013
Code: FileCreationInformation fci = new FileCreationInformation(); fci.Content = System.IO.File.ReadAllBytes(fileName); fci.Overwrite = true; fci.Url = fileUrl; File uploadFile = list.RootFolder.Files.Add(fci);
Error: The server does not allow messages larger than 2097152 bytes
Solution:
Using the power shell, you can set the MaxReceivedMessageSize and
MaxParseMessageSize and it works in 2013.
$ws = [Microsoft.SharePoint.Administration.SPWebService]::ContentService $ws.ClientRequestServiceSettings.MaxReceivedMessageSize = 209715200 $ws.ClientRequestServiceSettings.MaxParseMessageSize = 209715200 $ws.Update()
Sharepoint 2010
I used the same code in 2010 and it was not working here too but the error was a little different.
Error: 400 (Bad request)
I tried the above solution but it does not work for 2010 because there is no property named “MaxParseMessageSize” in 2010. When I tried the above solution in 2010 I got following error:
$ws = [Microsoft.SharePoint.Administration.SPWebService]::ContentService $ws.ClientRequestServiceSettings.MaxReceivedMessageSize = 209715200 $ws.ClientRequestServiceSettings.MaxParseMessageSize = 209715200 Property 'MaxParseMessageSize' cannot be found on this object; make sure it exists and is settable. At line:1 char:34 + $ws.ClientRequestServiceSettings. <<<< MaxParseMessageSize = 209715200 + CategoryInfo : InvalidOperation: (:) [], RuntimeException + FullyQualifiedErrorId : PropertyAssignmentException
Solution for 2010:
The only solution I was able to find was to use SaveBinaryDirect. So, after setting the following config:
$ws = [Microsoft.SharePoint.Administration.SPWebService]::ContentService
$ws.ClientRequestServiceSettings.MaxReceivedMessageSize = 209715200 $ws.Update()
You can use SaveBinaryDirect to upload a file larger than 2MB:
using (FileStream fs = new FileStream(@"Photo3MB.jpg", FileMode.Open)) { File.SaveBinaryDirect(context, "/documents/Photo3MB.jpg", fs, true); }
But remember, that this function does not return the reference to file and so you have to get the file yourself using GetFileByServerRelativeUrl, if you want to set some of the file properties. But it will always create two versions of the file in sharepoint unlike the first method which returns a file reference where you can set the properties and then check in your file to create just one version.