如何在C#中获取MS Word文件的详细信息

本文关键字:Word 文件 详细信息 MS 获取 | 更新日期: 2023-09-27 18:33:31

>我正在尝试使用 C# 获取所有打开文件的详细信息

   Microsoft.Office.Interop.Word.Application wordApp;
   wordApp = new Microsoft.Office.Interop.Word.Application();
   wordApp =(Microsoft.Office.Interop.Word.Application)System.Runtime.InteropServices.Marshal.GetActiveObject("Word.Application");
     for (int i = 0; i < wordApp .Windows.Count; i++)
       {
         string title;
         object a = i + 1;
         objWord.Windows[a].Activate();
         string fullName  =wordApp.Windows[a].Document.FullName.ToString();
        }

第一次它工作正常,并给我正确的objWord.window.count,但是在运行程序2,3次后,它总是显示零计数。

如何在C#中获取MS Word文件的详细信息

此问题可能是由于您创建 Word.Application 的新实例,然后尝试检索当前实例而引起的。这令人困惑,我不确定你想做什么。

相反,您应该尝试将当前实例放入 try/catch 中,如下所示:

Microsoft.Office.Interop.Word.Application wordApp = null;
try
{
     wordApp =(Microsoft.Office.Interop.Word.Application)System.Runtime.InteropServices.Marshal.GetActiveObject("Word.Application");
}
catch
{
    // Handle exceptions here or ignore the error, your choice
    MessageBox.Show("Could not find an existing instance of Word");
}
// READ THIS CAREFULLY
// If you didn't already get an instance of Word then create one
// I don't understand why you would do this as it would have 0 documents
if (wordApp == null)
{
    // I would not do this part, if you create a new instance you'll have 0 documents
    wordApp = new Microsoft.Office.Interop.Word.Application();
}
// Rest of your code goes here...