Bra*_*don 6 .net c# ms-word word-automation winforms
我有一个WinForms应用程序,我使用Word Automation通过模板构建文档,然后将它们保存到数据库.创建文档后,我从数据库中检索文档,将其写入临时目录中的文件系统,然后使用Word Interop服务打开文档.
加载了一个文档列表,用户只能打开每个文档的一个实例,但可以同时打开多个不同的文档.打开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.
Run Code Online (Sandbox Code Playgroud)
我使用以下代码打开文档并处理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);
}
}
Run Code Online (Sandbox Code Playgroud)
有没有人看到我正在做的任何错误,允许同时打开多个文件?我是Word Automation和Word Interop服务的新手,所以任何建议都表示赞赏.谢谢.
我通过这篇MSDN文章找到了解决方案:http://support.microsoft.com/kb/285885
您需要在调用Application.Quit()之前执行此操作;
_wordApplication.NormalTemplate.Saved = true;
Run Code Online (Sandbox Code Playgroud)
这可以防止Word尝试保存Normal.dotm模板.我希望这有助于其他人.
| 归档时间: |
|
| 查看次数: |
11548 次 |
| 最近记录: |