テンプレートを使用してドキュメントを作成し、データベースに保存するために Word Automation を使用している WinForms アプリケーションがあります。ドキュメントが作成されたら、データベースからドキュメントを取得し、それをファイル システムの一時ディレクトリに書き込み、Word Interop サービスを使用してドキュメントを開きます。
読み込まれたドキュメントのリストがあり、ユーザーは各ドキュメントの 1 つのインスタンスしか開くことができませんが、複数の異なるドキュメントを同時に開くことができます。1 つのドキュメントを開くときは、開いたり、保存したり、閉じたりするのに問題はありませんが、複数のドキュメントを同時に開くと、Word のインスタンスを閉じるときに次のエラーが表示されます。
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.
次のコードを使用してドキュメントを開き、BeforeDocumentClosed イベントを処理しています。
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);
}
}
複数のドキュメントを同時に開くことを許可するために私が行っていることを誰かが間違っていると思いますか? 私は Word Automation と Word Interop サービスにまったく慣れていないので、アドバイスをいただければ幸いです。ありがとう。