一、目的、构思
1.检测当前系统有没有安装某个程序,如果没有就重新安装。
2.在网上找到了两种方法,可惜都找不到需要检测的app。
二、code实现
1.查找注册列表方式。要在winform的project使用,在console project 貌似找不到Microsoft.Win32.RegistryKey。
public static bool CheckIfAppInstall(string appKeyName, out bool installResult)
{
installResult = false;
bool result = false;
try
{
Microsoft.Win32.RegistryKey uninstallNode = Microsoft.Win32.Registry.LocalMachine.OpenSubKey("SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Uninstall");
foreach (string subKeyName in uninstallNode.GetSubKeyNames())
{
Microsoft.Win32.RegistryKey subKey = uninstallNode.OpenSubKey(subKeyName);
object displayName = subKey.GetValue("DisplayName");
if (displayName != null)
{
if (displayName.ToString().Contains(appKeyName))
{
installResult = true;
}
}
}
result = true;
}
catch (Exception e)
{
string error = $"error in CheckIfAppInstall:{e.Message}";
throw new Exception(error);
}
return result;
}
2.使用MsiGetProductInfo。
static void Main()
{
StringBuilder result = new StringBuilder();
for (int index = 0; ; index++)
{
StringBuilder productCode = new StringBuilder(39);
if (MsiEnumProducts(index, productCode) != 0)
{
break;
}
foreach (string property in new string[] { "ProductName", "Publisher", "VersionString", })
{
int charCount = 512;
StringBuilder value = new StringBuilder(charCount);
if (MsiGetProductInfo(productCode.ToString(), property, value, ref charCount) == 0)
{
value.Length = charCount;
result.AppendLine(value.ToString());
}
}
result.AppendLine();
}
Console.WriteLine(result.ToString());
}
[DllImport("msi.dll", SetLastError = true)]
static extern int MsiEnumProducts(int iProductIndex, StringBuilder lpProductBuf);
[DllImport("msi.dll", SetLastError = true)]
static extern int MsiGetProductInfo(string szProduct, string szProperty, StringBuilder lpValueBuf, ref int pcchValueBuf);