目前,我正在使用此代码获取MS Word打开文档的列表:
List<string> doc_list = new List<string>();
try
{
Microsoft.Office.Interop.Word.Application WordObj;
WordObj = (Microsoft.Office.Interop.Word.Application)System.Runtime.InteropServices.Marshal.GetActiveObject("Word.Application");
for (int i = 0; i < WordObj.Windows.Count; i++)
{
object idx = i + 1;
Window WinObj = WordObj.Windows.get_Item(ref idx);
doc_list.Add(WinObj.Document.FullName);
}
}
catch
{
// No documents opened
}
如果文档已经“直接”打开,即双击它们,它就能正常工作。 但是,我注意到如果我直接从C#代码打开MS Word文档,例如:
Microsoft.Office.Interop.Word.Application word_app = new Microsoft.Office.Interop.Word.Application();
object inputFile = selected_doc; // "selected_doc" contains the document name
object confirmConversions = false;
object readOnly = false;
object visible = true;
object missing = Type.Missing;
Document doc = word_app.Documents.Open(
ref inputFile, ref confirmConversions, ref readOnly, ref missing,
ref missing, ref missing, ref missing, ref missing,
ref missing, ref missing, ref missing, ref visible,
ref missing, ref missing, ref missing, ref missing);
初始代码找不到以这种方式打开的任何文档,但我需要检测它。 为什么没找到?如何修改代码以便找到从C#打开的文档?
答案 0 :(得分:4)
在第一个代码中,您将获得已打开的Word实例中已打开文档的列表
Microsoft.Office.Interop.Word.Application WordObj;
WordObj = (Microsoft.Office.Interop.Word.Application)System.Runtime.InteropServices.Marshal.GetActiveObject("Word.Application");
在代码的第二部分中,您使用新 Word实例创建一个新文档
Microsoft.Office.Interop.Word.Application word_app = new Microsoft.Office.Interop.Word.Application();
因此,Word的两个实例无法打开和列出这些文件。
如果您希望第一种方法能够获取该文件,您可以尝试从Word的当前实例中打开该文件:
Microsoft.Office.Interop.Word.Application word_app;
word_app = (Microsoft.Office.Interop.Word.Application)System.Runtime.InteropServices.Marshal.GetActiveObject("Word.Application")
object inputFile = selected_doc; // "selected_doc" contains the document name
object confirmConversions = false;
object readOnly = false;
object visible = true;
object missing = Type.Missing;
Document doc = word_app.Documents.Open(
ref inputFile, ref confirmConversions, ref readOnly, ref missing,
ref missing, ref missing, ref missing, ref missing,
ref missing, ref missing, ref missing, ref visible,
ref missing, ref missing, ref missing, ref missing);