有没有办法用C#获取Word和Office STARTUP文件夹路径?

时间:2012-09-17 18:23:56

标签: c# ms-word ms-office

要获取Winodws Startup文件夹,我可以使用:

textBox1.Text = Environment.GetFolderPath(Environment.SpecialFolder.Startup);

是否有类似的方法来获取Office Startup文件夹和Word启动文件夹?

例如。以下是我正在寻找的两个例子:

"C:\Program Files (x86)\Microsoft Office\Office14\STARTUP"
"C:\Users\Jim\AppData\Roaming\Microsoft\Word\STARTUP"

由于

2 个答案:

答案 0 :(得分:2)

您需要查看注册表内部以查找该信息。有关详细信息,请查看this page。它将向您展示要查看的位置并在Visual Basic中为您提供示例。

答案 1 :(得分:1)

我在为Word插件安装.dotm文件时遇到此问题。我发现的最好方法是创建一个Word App对象并查询它的启动路径。这将使您获得与使用Application.StartupPath从Word中的VBA获得的文件夹相同的文件夹。获得启动路径后,您需要关闭Word App。这需要一些时间(比如一秒钟),你需要等到这个完成后再继续。以下是执行此操作的安装脚本代码:

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;