[英]How to make my application access the registry keys independent of whether its 32-bit or 64-bit?
[英]How to access 64-bit HKLM\Software Registry with a 32-bit C#.NET Application
所以我需要讀取 PC 上安裝的所有應用程序,但問題是其中一部分在 64 位注冊表值中,因此我無法使用 32 位應用程序讀取它。
因此,我需要將其設置為讀取 64 位值,這樣我就可以使用 32 位應用程序讀取 64 位注冊表值。 我將在這里展示我的例子。
這是我讀取注冊表中所有 32 位應用程序的方式:
string uninstallKey = @"SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall";
using (RegistryKey rk = Registry.LocalMachine.OpenSubKey(uninstallKey))
{
foreach (string skName in rk.GetSubKeyNames())
{
using (RegistryKey sk = rk.OpenSubKey(skName))
{
try
{
var displayName = sk.GetValue("DisplayName");
var size = sk.GetValue("EstimatedSize");
ListViewItem item;
if (displayName != null)
{
if (size != null)
item = new ListViewItem(new string[] { displayName.ToString(), size.ToString(), rk.OpenSubKey(skName).ToString() });
else
item = new ListViewItem(new string[] { displayName.ToString(), null, rk.OpenSubKey(skName).ToString() });
listInstalled.Items.Add(item);
}
}
catch (Exception ex)
{ }
}
}
}
這就是我讀取注冊表中所有 64 位應用程序的方式:
string uninstallKey = @"SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall";
RegistryKey regkey64 = RegistryKey.OpenBaseKey(RegistryHive.LocalMachine, RegistryView.Registry64);
RegistryKey rk64 = regkey64.OpenSubKey(uninstallKey);
foreach (string skName in rk64.GetSubKeyNames())
{
using (RegistryKey sk = rk64.OpenSubKey(skName))
{
try
{
var displayName = sk.GetValue("DisplayName");
var size = sk.GetValue("EstimatedSize");
ListViewItem item;
if (displayName != null)
{
if (size != null)
item = new ListViewItem(new string[] { displayName.ToString(), size.ToString(), rk64.OpenSubKey(skName).ToString() });
else
item = new ListViewItem(new string[] { displayName.ToString(), null, rk64.OpenSubKey(skName).ToString() });
listInstalled.Items.Add(item);
}
}
catch (Exception ex)
{ }
}
}
如果您沒有注意到這些差異,那么這次它們以粗體顯示:
32 位: RegistryKey rk = Registry.LocalMachine.OpenSubKey(uninstallKey)
64 位: RegistryKey regkey64 = RegistryKey.OpenBaseKey(RegistryHive.LocalMachine, RegistryView.Registry64); RegistryKey rk64 = regkey64.OpenSubKey(uninstallKey);
盡管它在 Microsoft 的站點中有記錄,但我決定將它寫在這里,因為這給我帶來了很多麻煩。 您無法讀取它的原因僅僅是因為它是一個 64 位值(32 位應用程序無法定期訪問它 - 以科學的名義確認自己;首先僅使用 32-位代碼,然后按 Alt-Enter>Build>取消選中“Prefer 32-bit”。現在再次運行它,您將看到它顯示所有 64 位應用程序)。
我希望這會很有用。 您可以在此處查看“技巧”並將其應用於您的代碼。 高音 :)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.