views:

99

answers:

1

So, I have this word template as a resource in my application. I want to open it to create new documents, but have no idea how to do this.

The following code doesn't work obviously, since the add method requires a filepath (and not the resource byte[] object...

object tFalse = false;
object missing = System.Reflection.Missing.Value;
Word.Application app = null;
Word.Document document = null;

object template = Resources.MyTemplate;
document = app.Documents.Add(ref template, ref tFalse, ref missing, ref missing);

But how do I access this resource file in a proper way?

any help is appreciated :)

A: 

Here is how I do it for the most part. I left out the work in between and left just the open and close.

private void ProcessWord()
{
    object missing = System.Reflection.Missing.Value;
    object readOnly = false;
    object isVisible = false;
    object fileName = "C:\\temp.dot";
    object fileNameSaveAs = "C:\\temp.doc";
    object fileFormat = WdSaveFormat.wdFormatRTF;
    object saveChanges = WdSaveOptions.wdDoNotSaveChanges;

    Microsoft.Office.Interop.Word.Application oWord = new Microsoft.Office.Interop.Word.Application();

    Documents oDocTmp = oWord.Documents;
    oWord.Visible = false;

    //Open the dot file as readonly
    Document oDoc = oDocTmp.Open(ref fileName, ref missing, ref readOnly, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref isVisible, ref missing, ref missing, ref missing, ref missing);

    //...do some work

    //Save the doc
    oDoc.SaveAs(ref fileNameSaveAs, ref fileFormat, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing);
    // close the open document 
    oDoc.Close(ref saveChanges, ref missing, ref missing);
    // quit word
    oWord.Quit(ref saveChanges, ref missing, ref missing);
}

You should also look into something to clean up the memory similar to:

GC.Collect();
GC.WaitForPendingFinalizers();
Marshal.FinalReleaseComObject(oWord);
Marshal.FinalReleaseComObject(oDocTmp);

Might not be the best practice, but it's been more successful than what it was before hand.

Tim Meers