简体   繁体   中英

Is there a way to get the the Word and Office STARTUP folder paths with C#?

To get the Winodws Startup folder I could use:

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

Is there a similar method for getting both the Office Startup folder, and the Word startup folder?

For example. Below are the two example of what I'm looking for:

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

Thanks

You will need to look inside the registry to find that information. Have a look at this page for more information. It will show you the places to look and give you examples in Visual Basic.

I had this problem when installing a .dotm file for a Word addin. The best way I found was to create a Word App object and query it for the startup path. This gets you the same folder you would get from VBA in Word using Application.StartupPath. Once you have the startup path you need to close the Word App. This takes some time (like a second) and you need to wait until this is done before proceeding. Here is the install script code to do this:

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;

Here is the same in C#. Here it waits for the process to finish or max 5 seconds. There is probably a better way to do the waiting but this works:

// 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);
}

At the top of the file you will need

 using System.Diagnostics;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM