在 MVC 上使用基于 Microsoft 站点的 WordprocessingDocument 后收到消息“MEMORY STREAM IS NOT EXPANDABLE”

Got a message " MEMORY STREAM IS NOT EXPANDABLE" after using WordprocessingDocument base on Microsoft site on MVC

目前,我在 Microsoft 站点上基于 "Search and replace text in a document part (Open XML SDK)"。我发现文件下载到我的驱动器后代码出现问题。

所以我打开那个文件并收到一条消息

MEMORY STREAM IS NOT EXPANDABLE at sw.Write(docText);

如何解决?

在 GenerateDocxHelper 中 class:

 private readonly MemoryStream _mem;
 private Dictionary<string, string> _dicData;

 public GenerateDocxHelper(string path)
 {
     _mem = new MemoryStream(System.IO.File.ReadAllBytes(path));
     _dicData = new Dictionary<string, string>();
 }

 public MemoryStream ReplaceTextInWord()
 {
     using (WordprocessingDocument wordDoc = WordprocessingDocument.Open(_mem, true))
        {


            string docText = null;
            using (StreamReader sr = new StreamReader(wordDoc.MainDocumentPart.GetStream()))
            {
                docText = sr.ReadToEnd();
            }


            foreach (var data in _dicData)
            {
                docText = docText.Replace(data.Key, data.Value);
            }

            using (StreamWriter sw = new StreamWriter(wordDoc.MainDocumentPart.GetStream(FileMode.Create)))
            {
                sw.Write(docText);
            }
        }

        _mem.Seek(0, SeekOrigin.Begin);

        return _mem;
 }

您应该使用 capacity = 0 创建 MemoryStream,这意味着它可以调整大小, 然后添加您从文件中读取的字节。

var allBytes = File.ReadAllBytes(path);

//this makes _mem resizeable 
_mem = new MemoryStream(0);

_mem.Write(allBytes, 0, allBytes.Length);

检查这个 answer