修改后的word文档不保存在内存流中

Modifed word document not saving in memorystream

我正在使用 Microsoft graph API 作为流从 SharePoint 获取一个 word 文档,并更改该文件中的一些内容并将保存的内容下载为一个文件,但是当我打开该文件时,修改后的内容是无法使用。下载的文件仍然显示原始内容。

       using (var memoryStream = new MemoryStream())
         {
            templateStream.Position = 0;
            // Copying the stream that I've got into memory stream
            await templateStream.CopyToAsync(memoryStream).ConfigureAwait(false);
            memoryStream.Position = 0;

            using (var wordDocument = WordprocessingDocument.Open(memoryStream, true))
            {
                RevisionAccepter.AcceptRevisions(wordDocument);
                var document = wordDocument.MainDocumentPart.GetXDocument();
                var content = document.Descendants(W.p).ToList();
                //based on the dictionary I've I am replacing the contents of the file
                foreach (var field in dataDictionary)
                {
                    var regex = new Regex(field.Key, RegexOptions.IgnoreCase);
                    OpenXmlRegex.Replace(content, regex, field.Value.ToString(), null);
                }
                //not showing the modified content
                wordDocument.Save();
                //this is also not updating the memorystream variable with the modified content
                wordDocument.MainDocumentPart.Document.Save();
                memoryStream.Position = 0;
                await memoryStream.FlushAsync().ConfigureAwait(false);
            }

            var result = memoryStream.ToArray();
            memoryStream.Flush();
            return result;
        }

一旦我从上面的代码中得到字节数组,我就会使用我的控制器中的这一行下载文件

  return File(returnResponse, System.Net.Mime.MediaTypeNames.Application.Octet, $"Test- 
               {System.DateTime.Now}.docx");

我做错了什么?

MainDocumentPart上的 you need to call PutXDocument()方法所述,您的更改将成功反映出来,因为目前您正在进行更改,但没有将它们提交到所需的文档中。