我在为 Word 插件安装 .dotm 文件时遇到了这个问题。我发现最好的方法是创建一个 Word App 对象并查询它的启动路径。这将为您提供与使用 Application.StartupPath 从 Word 中的 VBA 获得的文件夹相同的文件夹。获得启动路径后,您需要关闭 Word 应用程序。这需要一些时间(比如一秒钟),您需要等到完成后再继续。这是执行此操作的安装脚本代码:
try
  set wordApp = CoCreateObject("Word.Application");
  wordStartupPath = wordApp.StartupPath;
  // Without delays wordApp.quit sometimes fails
  Delay(1);
  wordApp.quit;
  Delay(2);
  set wordApp = NOTHING;
catch
   MessageBox("Word Startup Path Cannot be found", INFORMATION);
endcatch;
在 C# 中也是如此。在这里它等待进程完成或最多 5 秒。可能有更好的方法来等待,但这有效:
// Get the startup path from Word
Type wordType = Type.GetTypeFromProgID("Word.Application");
object wordInst = Activator.CreateInstance(wordType);
string wordStartupPath = (String)wordType.InvokeMember("StartupPath", BindingFlags.DeclaredOnly |
                        BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.GetProperty, null,
                        wordInst, null); 
Thread.Sleep(1000);
wordType.InvokeMember("Quit", BindingFlags.InvokeMethod, null, wordInst, null);
// Make sure Word has quit or wait 5 seconds
for (int i = 0; i < 50; i++)
{
    Process[] processes = Process.GetProcessesByName("winword");
    if (processes.Length == 0)
        break;
    Thread.Sleep(100);
}
在文件的顶部,您将需要
 using System.Diagnostics;