Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Currently, I was base on "Search and replace text in a document part (Open XML SDK)" on the Microsoft site. I've realized that the code got an issue after the file has downloaded to my drive.

So I opened that file and got a message

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

How to fix that?

In 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;
 }
like image 313
hoang lethien Avatar asked Sep 12 '25 18:09

hoang lethien


1 Answers

You should create the MemoryStream with capacity = 0 which means it is resizeable, and then add the bytes you have read from the file.

var allBytes = File.ReadAllBytes(path);

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

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

Check this answer

like image 51
csharpwinphonexaml Avatar answered Sep 15 '25 09:09

csharpwinphonexaml