Search code examples
c#ms-wordembedded-resource

How to open embedded resource word document?


I have a embedded word template document in my project, I added it as resource (Resources.resx -> Add resource -> Add existing file) and now I want to open it something like this

Microsoft.Office.Interop.Word.Application application = new Microsoft.Office.Interop.Word.Application();
Document document = application.Documents.Open(Properties.Resources.MyDoc);

But unfortunately the Microsoft.Office.Interop.Word.Application doesn't work with byte arrays and I can't set MyDoc to it.


Solution

  • Word can only open files that exist in the filesystem, it cannot work entirely from-memory.

    Do something like this:

    String fileName = Path.GetTempFileName();
    File.WriteAllBytes( fileName , Properties.Resources.MyDoc );
    application.Documents.Open( fileName  );
    

    Then when you've detected Word has been closed, delete the file:

    File.Delete( fileName );
    

    It might be an idea (for performance reasons) to embed the Word document as an Embedded Resource instead of a Byte[] array within a resx file, like so:

    Assembly thisExe = System.Reflection.Assembly.GetExecutingAssembly();
    System.IO.Stream resourceStream = thisExe.GetManifestResourceStream("MyDoc.docx");
    // copy the stream to a new FileStream, then open Word as-before