我有一个简单的测试程序,使用Microsoft Word Interop从同义词字典获取单词的意思:
using System;
using Word = Microsoft.Office.Interop.Word;
class Program
{
static void Main(string[] args)
{
string word = "elite"; // = "common";
var app = new Word.Application();
var synInfo = app.SynonymInfo[word, Word.WdLanguageID.wdEnglishUS];
if (synInfo.Found && synInfo.MeaningCount > 0)
{
foreach (var meaning in synInfo.MeaningList as Array)
Console.WriteLine(meaning.ToString());
}
// release memory and quit Word app... (see below)
}
}
我尝试在Visual Studio 2010中使用.Net 4.0,引用Office 12 PIA,并在Microsoft Office 2010和Microsoft Office 2013预览版上测试了此方法。对于超过150,000个不同的单词,此方法运行良好。但是我注意到对于某些单词,get_SynonymInfo方法会抛出异常:
Unhandled Exception: System.Runtime.InteropServices.COMException: Insufficient memory or disk space.
at Microsoft.Office.Interop.Word.ApplicationClass.get_SynonymInfo(String Word, Object& LanguageID)
at WordInteropTest.Program.Main(String[] args) in Program.cs:line 11
我知道这些词会导致异常:
- elite(但"elites"可行)
- near
- tuck
- tucks
- walking
- onboard
- horrified
这与异常无关,只是为了提供完整的源代码,我确实释放了内存并正常退出Word应用程序。当我退出测试程序时,进程列表中没有剩余的msword.exe。
// release memory and quit Word app... (continuing from above)
System.Runtime.InteropServices.Marshal.FinalReleaseComObject(synInfo);
app.Quit(Word.WdSaveOptions.wdDoNotSaveChanges);
System.Runtime.InteropServices.Marshal.FinalReleaseComObject(app);
在微软Word中手动使用同义词词典可以为所有单词提供正确的结果。
如何避免异常并使用Interop代码获得结果?是否有使用其他API的有效替代方法?
更新:我在本地编程网络论坛上被告知这段代码适用于Office 2007。令我惊讶的是,它确实有效。但是,根据本问题所述,在Office 2010和2013预览版中,它无法正常工作,至少在我的计算机/虚拟机上不行。然后我尝试引用Office 14 PIA而不是Office 12,但在Office 2013 Preview下,它的行为与前者相同。