4

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;
 }
Tieson T.
  • 20,774
  • 6
  • 77
  • 92
hoang lethien
  • 117
  • 2
  • 10

1 Answers1

15

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

csharpwinphonexaml
  • 3,659
  • 10
  • 32
  • 63