0

Hi I am trying to make working this piece of code, after the copy of the word file template into a memory stream, read it and replace some text, I would convert the stream writer to byte array which will be used to download the result. Thanks in advance

public byte[] GetWordFile()
    {
        try
        {
            string sourceFile = Path.Combine("C:/[...]/somefile.docx");

            using (MemoryStream inStream = new MemoryStream())
            {
                using (Stream fs = File.Open(sourceFile, FileMode.Open, FileAccess.Read))
                {
                    fs.CopyTo(inStream);
                }

                using (WordprocessingDocument wordDoc = WordprocessingDocument.Open(inStream, true))
                {
                    string docText = null;
                    using (StreamReader sr = new StreamReader(wordDoc.MainDocumentPart.GetStream()))
                    {
                        docText = sr.ReadToEnd();
                    }

                    docText = docText.Replace("numpol", "HAHAHHAHA");

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

                        sw.BaseStream.CopyTo(outStream);

                        outStream.Position = 0;

                        return outStream.ToArray();
                    }
                }
            }

        }
        catch (Exception ex)
        {
           ///...
        }
    }
ADC
  • 617
  • 7
  • 14
  • But word documents are not plain text. Older versions (pre-Office 2007) have a binary format (file extension: *.doc) while Office 2007 and later versions are Open Xml (file extension: *.docx). You can check out this SDK from Microsoft (or use any other Open XML API since it is a standard) to "Replace" text or to achieve any other manipulations: https://learn.microsoft.com/en-us/office/open-xml/open-xml-sdk – Oguz Ozgul Mar 28 '20 at 17:56
  • @OguzOzgul hi the replacement is working fine, if I use filesystem file targets I can see the replacements, the problem here is just how to download the streamWriter – ADC Mar 28 '20 at 18:02
  • Ok sorry, you are already using a library :) Sorry, really. What kind of web application do you have? Web Forms or MVC Application? I mean, will you serve it through a controller? There are numerous samples on stack overflow, check the marked answer in [this one](https://stackoverflow.com/questions/3604562/download-file-of-any-type-in-asp-net-mvc-using-fileresult) – Oguz Ozgul Mar 28 '20 at 18:08

0 Answers0