MemoryStream 在 C# MVC 项目中将空文件上传到 SharePoint

MemoryStream Uploading Empty File to SharePoint in C# MVC Project

我正在测试将文件上传到 SharePoint 的功能。我正在使用以下代码:

        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);
        }

已将名称正确的文件上传到正确的位置。但是,文件是空白的。

UploadedFile 是我的 ViewModel 中的 属性 =>

public HttpPostedFileBase UploadedFile { get; set; }

我的表单中还有一个名为 UploadedFile 的文件输入类型,我用它来 select 要上传的文件 =>

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

我的问题是:为什么我上传的文件是空白的?

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 属性回零:

vm.UploadedFile.InputStream.CopyTo(target);

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

Microsoft.SharePoint.Client.File.SaveBinaryDirect(....);