C# 检查当前系统已安装的程序app/两种方法检测

一、目的、构思

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

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值