0

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 CSOM approach.

1
public void UploadDocument_FromStream(Stream file, string fileName)
    {
        using (var clientContext = OpenConnectionToSharePoint())
        {
            var webContext = clientContext.Web.Context;

            if (file == null) throw new Exception("Stream cannot be null");
            if (webContext.HasPendingRequest) webContext.ExecuteQuery();

            var list = clientContext.Web.Lists.GetByTitle(SharePointRoot);
            clientContext.Load(list.RootFolder);
            clientContext.ExecuteQuery();

            var fileUrl = Path.Combine(list.RootFolder.ServerRelativeUrl, fileName);

            Microsoft.SharePoint.Client.File.SaveBinaryDirect(
                clientContext, fileUrl, file, true);
        }
    }
| improve this answer | |
  • may be, another option is FileCreationInformation. – Kosikovec Jul 14 '16 at 9:45
-1

Another option is FileCreationInformation...

function File Upload(ClientContext ctx, string folderRelativeUrl, string fileName, Stream data)
{
    var ci = new FileCreationInformation()
    {
        ContentStream = fs.Value,
        Overwrite = true,
        Url = folderRelativeUrl + "/" + fileName
    };
    var newFile = destinationInfo.Folder.Files.Add(ci);
    ctx.ExecuteQuery();
    return newFile;
}
| improve this answer | |

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.