Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

MemoryStream Uploading Empty File to SharePoint in C# MVC Project

I am testing out the ability to upload a file to SharePoint. I am using the following code:

        var targetSiteURL = @"https://company.sharepoint.com/sites/ProjectRoom";

        var login = "user@company.com";
        
        var password = "PWD123!";

        var securePassword = new SecureString();

        foreach (var c in password)
        {
            securePassword.AppendChar(c);
        }

        var ctx = new ClientContext(targetSiteURL)
        {
            Credentials = new SharePointOnlineCredentials(login, securePassword)
        };

        var fileName = vm.UploadedFile.FileName;

        using (var target = new MemoryStream())
        {
            vm.UploadedFile.InputStream.CopyTo(target);

            Microsoft.SharePoint.Client.File.SaveBinaryDirect(ctx, $"/sites/ProjectRoom/Project Room Test/{fileName}", target, true);
        }

A file is uploaded with the correct name to the correct location. However, the file is blank.

UploadedFile is a property in my ViewModel =>

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

public HttpPostedFileBase UploadedFile { get; set; }

I also have an input type of file named UploadedFile in my form, which I use to select the file to upload =>

<input type="file" name="UploadedFile" id="UploadedFile"/>

My question is: Why is the file that I upload blank?

>Solution :

A MemoryStream has an internal pointer to the next byte to read. After inserting bytes into it, you need to reset it back to the start or the consuming app may not realise and will read it as empty. To reset it, just set the Position property back to zero:

vm.UploadedFile.InputStream.CopyTo(target);

// Add this line:
target.Position = 0;

Microsoft.SharePoint.Client.File.SaveBinaryDirect(....);
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading