這裏是我如何做到這一點大部分。我離開了工作之間,離開只是打開和關閉。
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);
}
你也應該看看到的東西清理類似的記憶:
GC.Collect();
GC.WaitForPendingFinalizers();
Marshal.FinalReleaseComObject(oWord);
Marshal.FinalReleaseComObject(oDocTmp);
可能不是最好的做法,但它已經比它的前手取得更大的成功。