簡體   English   中英

迭代注冊表項

[英]Iterate through registry entries

正如這里建議的那樣,我需要遍歷條目

HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall\

找出我的應用程序的安裝路徑。 如何迭代,以便我可以找到給定DisplayNameInstallLocation值。 如何在C#中高效地完成它。

以下是實現目標的代碼:

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

編輯:有關查找應用程序安裝路徑的更全面方法,請參閱此方法 ,它演示了注釋中建議的using處置。 https://stackoverflow.com/a/26686738/495455

using (RegistryKey key = Registry.LocalMachine.OpenSubKey(@"Whater\The\Key"))
{
  if (key != null)
  {
    foreach (string ValueOfName in key.GetValueNames())
    {
      try
      {
         bool Value = bool.Parse((string)key.GetValue(ValueOfName));
      }
      catch (Exception ex) {}
    }
 }
}

使用bool強制轉換:D - 所以字符串應該是True或False。

對於用戶注冊表配置單元,請使用Registry.CurrentUser而不是Registry.LocalMachine

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM