Tuesday, March 01, 2005

A code snippet in C# to get the installed path for MS Office using Registry Keys

private string GetOfficeAppPath(string sProgId, string sEXE)
{
//Returns path of the Office application. e.g.
//GetOfficeAppPath("Access.Application", "msaccess.exe") returns
//full path to Microsoft Access. Approach based on Q240794.
//Returns null if path not found in registry.

// Enable exception handler:
try
{
Microsoft.Win32.RegistryKey oReg =
Microsoft.Win32.Registry.LocalMachine;
Microsoft.Win32.RegistryKey oKey = null;
string sCLSID = null;
string sPath = null;
int iPos = 0;

// First, get the clsid from the progid from the registry key
// HKEY_LOCAL_MACHINE\Software\Classes\\CLSID:
oKey = oReg.OpenSubKey(@"Software\Classes\" + sProgId + @"\CLSID");
sCLSID = oKey.GetValue("").ToString();
oKey.Close();

// Now that we have the CLSID, locate the server path at
// HKEY_LOCAL_MACHINE\Software\Classes\CLSID // {xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxx}\LocalServer32:
oKey = oReg.OpenSubKey(@"Software\Classes\CLSID\" + sCLSID +
@"\LocalServer32");
sPath = oKey.GetValue("").ToString();
oKey.Close();

// Remove any characters beyond the exe name:
iPos = sPath.ToUpper().IndexOf(sEXE.ToUpper()); // 0-based position
sPath = sPath.Substring(0, iPos + sEXE.Length);
return sPath.Trim();
}
catch
{
return null;
}
}

No comments: