绝大多数软件,基本上都会在注册表中记录自己的名字和安装路径信息。
在注册表中记录这些信息的位置是:
HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\App Paths
因此,我们只要能访问到注册表的这个位置,就可以获取到某些软件的名称和安装路径信息。
public enum Softwares
{Excel, //Office Excel
Winword, //Office Word
Msaccess, //Office Access
Powerpnt, //Office PowerPoint
Outlook, //Office Outlook
Infopath, //Office InfoPath
Mspub, //Office Publisher
Visio, //Office Visio
Iexplore, //IE
Itunes //Apple ITunes
//.........
}
public class SoftwareOperator
{
//When you do not want to use string name, then use the Enum instead
public static bool TryGetSoftwarePath(Softwares softName, out string path)
{
return TryGetSoftwarePath(softName.ToString(), out path);
}
public static bool TryGetSoftwarePath(string softName, out string path)
{
string strPathResult = string.Empty;
string strKeyName = ""; //"(Default)" key, which contains the intalled path
object objResult = null;
RegistryKey regKey = null;
RegistryKey regSubKey = null;
try
{
//Read the key
regKey = Registry.LocalMachine;
regSubKey = regKey.OpenSubKey(@"SOFTWARE\Microsoft\Windows\CurrentVersion\App Paths\" + softName + ".exe", false);
//Read the path
var regValueKind = RegistryValueKind.Unknown;
if (regSubKey != null)
{
objResult = regSubKey.GetValue(strKeyName);
regValueKind = regSubKey.GetValueKind(strKeyName);
}
//Set the path
if (regValueKind == RegistryValueKind.String)
{
if (objResult != null) strPathResult = objResult.ToString();
}
}
catch (System.Security.SecurityException ex)
{
throw new System.Security.SecurityException("You have no right to read the registry!", ex);
}
catch (Exception ex)
{
throw new Exception("Reading registry error!", ex);
}
finally
{
regKey?.Close();
regSubKey?.Close();
}
if (strPathResult != string.Empty)
{
//Found
path = strPathResult;
return true;
}
//Not found
path = null;
return false;
}
}
}