views:

891

answers:

2

I have loaded a memorystream with a word document and I want to be able to alter specific text within the memorystream and save it back to the word document, like search and replace functionality. Please can anyone help me with this as I don't want to use the Word Interop libraries. I have the code to load and save the document already, please see below. The problem is, if I convert the memorystring to a string and use the string replace method, when I save the string all the formatting within the word document is lost and when I open the document all it shows is black boxes all over the place.

        private void ReplaceInFile(string filePath, string searchText, string replaceText)
    {
        byte[] inputFile = File.ReadAllBytes(filePath);
        MemoryStream memory = new MemoryStream(inputFile);

        byte[] data = memory.ToArray();

        string pathStr = Request.PhysicalApplicationPath + "\\Docs\\OutputDocument.doc";
        FileInfo wordFile = new FileInfo(pathStr);
        FileStream fileStream = wordFile.Open(FileMode.Create, FileAccess.Write, FileShare.None);

        fileStream.Write(data, 0, data.Length);

        fileStream.Close();

        memory.Close();
    }
+5  A: 

You will have to use the Word interop libraries - or at least something similar. It's not like Word documents are just plain text documents - they're binary files. Converting the bytes into a string and doing a replace that way is going to break the document completely.

With the new open formats you may be able to write your own code to parse them, but it's going to be significantly harder than using a library.

Jon Skeet
A: 

I copied the code from sample code on the internet. So That is why memorystream was used as I had no idea how to do it. My issue is the company I work for doesn't want to use the word interop as sometimes they have found that word can display popup dialog boxes on occassion that prevents the coded functionality from executing. This is why I want to look at ways of achieving a mail merge functionality but in a programmatical way. I did do a very similar thing to what I want to do here many years ago but in Delphi not C# and I have typically lost the code. So if anyone can shed any light on this then I would be grateful.

SB