I'm trying to duplicate a file from one library to another within a Remote Event Receiver.
When reaching the UploadFile-function, I get the following error:
Specified argument was out of the range of valid values. Parameter name: bytesToCopy
Information about the function can be found here. It has the following signature:
public static Microsoft.SharePoint.Client.File UploadFile (this Microsoft.SharePoint.Client.Folder folder, string fileName, System.IO.Stream stream, bool overwriteIfExists);
My code is:
using (System.IO.MemoryStream stream = new System.IO.MemoryStream())
{
    ClientResult<Stream> data = curItem.File.OpenBinaryStream();
    clientContext.ExecuteQuery();
    if (data != null && data.Value != null)
    {
         data.Value.CopyTo(stream);
         UploadedFile = destinationList.RootFolder.UploadFile(curItem.File.Name.ToString(), stream, true);
    }
}
As a note: curItem, destinationList and curItem.File are all loaded in the context.
Edit, complete error:
   at Microsoft.SharePoint.Client.ClientRequest.ProcessResponseStream(Stream responseStream)
   at Microsoft.SharePoint.Client.ClientRequest.ProcessResponse()
   at Microsoft.SharePoint.Client.ClientContextExtensions.ExecuteQueryImplementation(ClientRuntimeContext clientContext, Int32 retryCount, Int32 delay, String userAgent)
   at Microsoft.SharePoint.Client.FileFolderExtensions.UploadFile(Folder folder, String fileName, Stream stream, Boolean overwriteIfExists)
   at PG.SHP.SCE.QCSPAddInWeb.Services.AppEventReceiver.HandleItemCheckedIn(SPRemoteEventProperties properties) in C:\Users\OBJ_JDWR\Source\Workspaces\SharePoint\SCE\Main\Source\PG.SHP.SCE\Source\PG.SHP.SCE.QCSPAddInWeb\Services\AppEventReceiver.svc.cs:line 288
Line 288:

How to get rid of the error?
A quick google search lead me to this article
Someone had a similar problem (although he figured it had to do with file size) and solved it by resetting the stream before sending it to SharePoint:
using (var stream = content)
{
    ...
    stream.Seek(0, SeekOrigin.Begin); // <-- The missing statement
    ...
}
Hope that works for you as well :)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With