-1

I am creating a method to UploadDocument_FromStream() method which has one parameter -- Stream file.

I am having trouble trying to keep my SharePoint connection open to allow me to upload my Stream file to SharePoint. I think the issue is due to the fact that I am executing a query then trying to upload to SharePoint.

Is this the best way to handle Uploading to SharePoint with a MemoryStream?


UploadDocument_FromStream()

public void UploadDocument_FromStream(Stream file)
    {
        using (var clientContext = OpenConnectionToSharePoint())
        {
            if (file == null) throw new Exception("Stream cannot be null");

            using (clientContext)
            {
                var list = clientContext.Web.Lists.GetByTitle("Documents");
                clientContext.Load(list.RootFolder);
                clientContext.ExecuteQuery();

                Microsoft.SharePoint.Client.File.SaveBinaryDirect(clientContext, "/shared documents/test.pdf", file, true);
            }
     }

Also should note - that I am using SharePoint.Client.dll or COM approach.

1

1 Answer 1

0

SharePoint CSOM API utilizes internal query queue to support Request Batching via ClientRuntimeContext.Load method. But both File.OpenBinaryDirect and File.SaveBinaryDirect methods are executed directly and require internal queue to be empty. For that purpose you could utilize the following checking before invoking File.SaveBinaryDirect method:

if (ctx.HasPendingRequest)
    ctx.ExecuteQuery();

The following example shows how to save a file stream into documents library

var list = ctx.Web.Lists.GetByTitle(listTitle);
ctx.Load(list.RootFolder);
ctx.ExecuteQuery();


var fileName = System.IO.Path.GetFileName(path);
byte[] data = System.IO.File.ReadAllBytes(path);
MemoryStream stream = new MemoryStream(data);    
var fileUrl = Path.Combine(list.RootFolder.ServerRelativeUrl, fileName);

if (ctx.HasPendingRequest)
     ctx.ExecuteQuery();
Microsoft.SharePoint.Client.File.SaveBinaryDirect(ctx, fileUrl, stream, true); 
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.