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 = "[email protected]";
        
        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 =>

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 1:

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(....);