迭代注册表项

Nem*_*emo 25 c#

正如这里建议的那样,我需要遍历条目

HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall\
Run Code Online (Sandbox Code Playgroud)

找出我的应用程序的安装路径.如何迭代,以便我可以找到给定DisplayNameInstallLocation值.如何在C#中高效地完成它.

Mik*_*e J 32

以下是实现目标的代码:

class Program
{
    static void Main(string[] args)
    {
        RegistryKey key = Registry.LocalMachine.OpenSubKey("Software\\Microsoft\\Windows\\CurrentVersion\\Uninstall");
        foreach (var v in key.GetSubKeyNames())
        {
            Console.WriteLine(v);

            RegistryKey productKey = key.OpenSubKey(v);
            if (productKey != null)
            {
                foreach (var value in productKey.GetValueNames())
                {
                    Console.WriteLine("\tValue:" + value);

                    // Check for the publisher to ensure it's our product
                    string keyValue = Convert.ToString(productKey.GetValue("Publisher"));
                    if (!keyValue.Equals("MyPublisherCompanyName", StringComparison.OrdinalIgnoreCase))
                        continue;

                    string productName = Convert.ToString(productKey.GetValue("DisplayName"));
                    if (!productName.Equals("MyProductName", StringComparison.OrdinalIgnoreCase))
                        return;

                    string uninstallPath = Convert.ToString(productKey.GetValue("InstallSource"));

                    // Do something with this valuable information
                }
            }
        }

        Console.ReadLine();
    }
}
Run Code Online (Sandbox Code Playgroud)

编辑:有关查找"应用程序安装路径"的更全面方法,请参阅此方法,它将using按照注释中的建议演示处理. /sf/answers/1868071691/

  • 你可能想在`RegistryKey`实例上调用`Dispose`,或者更好的是,将它们包装在`using`块中. (3认同)