在MVC的Microsoft网站上使用WordprocessingDocument后,收到消息“内存条不可扩展”

时间:2018-08-25 15:58:00

标签: c# asp.net-mvc asp.net-mvc-4

当前,我基于Microsoft网站上的“搜索并替换文档部分中的文本(Open XML SDK)”。我已经意识到文件下载到驱动器后,代码出现了问题。

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

  

在sw.Write(docText)处无法扩展内存流;

该如何解决?

在GenerateDocxHelper类中:

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

1 个答案:

答案 0 :(得分:1)

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

var allBytes = File.ReadAllBytes(path);

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

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

选中此answer