I have a WinForms application where I use Word Automation to create documents through a template and then save them to a database. After creating the document, I extract the document from the database, write it to the file system in the temporary directory, and then open the document using Word Interop services.
There is a list of downloaded documents, and the user can open only one copy of each document, but can simultaneously open several different documents. I have no problem opening, saving and closing when they open one document, however, when they open several documents at the same time, I get the following error when closing any of my Word instances:
The file is in use by another application or user. (C:\...\Templates\Normal.dotm) This error is commonly encountered when a read lock is set on the file that you are attempting to open.
I use the following code to open a document and handle the BeforeDocumentClosed event:
public void OpenDocument(string filePath, Protocol protocol, string docTitle, byte[] document) { _protocol = protocol; documentTitle = docTitle; _path = filePath; if (!_wordDocuments.ContainsKey(_path)) { FileUtility.WriteToFileSystem(filePath, document); Word.Application wordApplication = new Word.Application(); wordApplication.DocumentBeforeClose += WordApplicationDocumentBeforeClose; wordApplication.Documents.Open(_path); _wordDocuments.Add(_path, wordApplication); } _wordApplication = _wordDocuments[_path]; _currentWordDocument = _wordApplication.ActiveDocument; ShowWordApplication(); } public void ShowWordApplication() { if (_wordApplication != null) { _wordApplication.Visible = true; _wordApplication.Activate(); _wordApplication.ActiveWindow.SetFocus(); } } private void WordApplicationDocumentBeforeClose(Document doc, ref bool cancel) { if (!_currentWordDocument.Saved) { DialogResult dr = MessageHandler.ShowConfirmationYnc(String.Format(Strings.DocumentNotSavedMsg, _documentTitle), Strings.DocumentNotSavedCaption); switch (dr) { case DialogResult.Yes: SaveDocument(_path); break; case DialogResult.Cancel: cancel = true; return; } } try { if (_currentWordDocument != null) _currentWordDocument.Close(); } finally { Cleanup(); } } public void Cleanup() { if (_currentWordDocument != null) while(Marshal.ReleaseComObject(_currentWordDocument) > 0); if (_wordApplication != null) { _wordApplication.Quit(); while (Marshal.ReleaseComObject(_wordApplication) > 0); _wordDocuments.Remove(_path); } }
Does anyone see something wrong that I am doing to open multiple documents at the same time? I am new to Word Automation and Word Interop services, so any advice is appreciated. Thanks.
Brandon
source share