Timeout error during file upload in document library using managed client object model : Microsoft.SharePoint.Client.File.SaveBinaryDirect

There are mainly 2 ways to upload files in sharepoint document library using client object model. One way is to use Microsoft.SharePoint.Client.File.SaveBinaryDirect method and other one is to use documentLibraryObject.RootFolder.Files.Add(newFileCreationInformation) method. documentLibraryObject.RootFolder.Files.Add method increases the message size because of BASE64 encoding.

While uploading large files, Microsoft.SharePoint.Client.File.SaveBinaryDirect can be used, in order to avoid increased message size. While doing so, there is possibility that you may get exception saying "The underlying connection was closed: A connection that was expected to maintain their closed down the server". The reason for this is sometimes WebRequest gets time out while uploading the large file.

To solve this problem, set the time out of the context before calling the Microsoft.SharePoint.Client.File.SaveBinaryDirect method.

 context.RequestTimeout = 3600000; // Time in milliseconds
Microsoft.SharePoint.Client.File.SaveBinaryDirect(context, relativePath, filestream, overWrite);.

Reason behind setting context.RequestTimeout is, internally while creating the web request object, value of context.RequestTimeout will be copies to webRequest.Timeout.