Upload a document to a SharePoint list from Managed Client Side Object Model

Referred URL 
http://pramodixit.wordpress.com/2013/07/23/upload-a-document-to-a-sharepoint-list-from-managed-client-side-object-model

Error Descriptions
Cannot invoke HTTP DAV request. There is a pending query
The request message is too big. The server does not allow messages larger than 2097152 bytes.

Solution 

The first method uses a client library batch mechanism.
private static void UsingBatchMechanism(ClientContext clientContext)
{
clientContext.Credentials = credentials;
Web site = clientContext.Web;
            FileCreationInformation newFile = new FileCreationInformation();
newFile.Content = System.IO.File.ReadAllBytes(@”C:\\TestUpload.pptx”);
newFile.Url = “TestUpload.pptx”;
            List docs = site.Lists.GetByTitle(“Shared Documents”);
Microsoft.SharePoint.Client.File uploadFile = docs.RootFolder.Files.Add(newFile);
clientContext.Load(uploadFile);
clientContext.ExecuteQuery();
}
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. 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.
private static void UsingSaveBinaryDirect(ClientContext clientContext)
{
ClientContext clientContext = new ClientContext(siteurl)
List CurrentList = clientContext.Web.Lists.GetByTitle(libraryName);
clientContext.Load(CurrentList.RootFolder);
clientContext.ExecuteQuery();
using (FileStream fileStream = new FileStream(fileName, FileMode.Open))
{
Microsoft.SharePoint.Client.File.SaveBinaryDirect(clientContext, CurrentList.RootFolder.ServerRelativeUrl.ToString() + “/” + fileName.Split(‘\\’)[1], fileStream, true);
}
}
We need to load the document libraries’ root folder before we execute the query. I have changed the code accordingly and it worked fine for me, I have tested it with Uploading 16.9 MB file and it worked. Note: This will not give you the error, “Cannot invoke HTTP DAV request. There is a pending query” 

You May Also Like

0 comments