检查注册表项是否存在 [英] Checking if a registry key exists

查看:180
本文介绍了检查注册表项是否存在的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在寻找一个干净的方式来检查注册表项是否存在。我假设RegOpenKey会失败,如果我试图打开一个不存在的密钥,但它不。



我可以使用字符串处理查找和打开我正在寻找的一个父键,然后枚举该键的子键,以找出我感兴趣的一个存在,但感觉两个像一个性能猪,像一个奇怪的方式必须实现这样一个简单的函数。



我想你可以使用RegQueryInfoKey这个不知何故,但MSDN没有给出太多的细节,如果可能的话。



更新:我需要解决方案在直接win32 api,而不是托管代码,.NET或任何其他库。



MSDN中的文档似乎表明您应该能够打开一个读取权限的键,并且如果它不存在则会收到一个错误,例如:

  lResult = RegOpenKeyEx(hKeyRoot,lpSubKey,0,KEY_READ,& hKey); 

if(lResult!= ERROR_SUCCESS)
{
if(lResult == ERROR_FILE_NOT_FOUND){



更新2 :我的确切代码是this:

  HKEY subKey = nullptr; 
LONG result = RegOpenKeyEx(key,subPath.c_str(),0,KEY_READ,& subKey);
if(result!= ERROR_SUCCESS){

...但结果显示为ERROR_SUCCESS即使我已经输入了一个不存在的键。



更新3 :看起来你们是对的。这在一个特定的测试示例(神秘地)失败。如果我尝试任何其他键,它返回正确的结果。双击它与注册表编辑器仍然不显示键。

解决方案

首先不要担心像这样的东西的性能。除非你每秒查询100次,否则速度会更快。过早优化会导致各种头痛。



如果找到键,RegOpenKeyEx将返回ERROR_SUCCESS。只要检查这个常数,你很好去。


I am looking for a clean way to check if a registry key exists. I had assumed that RegOpenKey would fail if I tried to open a key that didn't exist, but it doesn't.

I could use string processing to find and open the parent key of the one I'm looking for, and then enumerating the subkeys of that key to find out if the one I'm interested in exists, but that feels both like a performance hog and like a weird way to have to implement such a simple function.

I'd guess that you could use RegQueryInfoKey for this somehow, but MSDN doesn't give too many details on how, in case it's possible.

Update: I need the solution in straight win32 api, not in managed code, .NET or any other library.

The docs in MSDN seem to indicate that you should be able to open a key for read permission and get an error if it doesn't exist, like this:

lResult = RegOpenKeyEx (hKeyRoot, lpSubKey, 0, KEY_READ, &hKey);

if (lResult != ERROR_SUCCESS) 
{
    if (lResult == ERROR_FILE_NOT_FOUND) {

However, I get ERROR_SUCCESS when I try this.

Update 2: My exact code is this:

HKEY subKey = nullptr;
LONG result = RegOpenKeyEx(key, subPath.c_str(), 0, KEY_READ, &subKey);
if (result != ERROR_SUCCESS) {

... but result comes out as ERROR_SUCCESS, even though I've put in a key that does not exist.

Update 3: It looks like you guys are right. This fails on one specific test example (mysteriously). If I try it on any other key, it returns the correct result. Doublechecking it with the registry editor still does not show the key. Dunno what to make of that at all.

解决方案

First of all don't worry about performance for stuff like this. Unless you are querying it 100x per sec, it will be more than fast enough. Premature optimization will cause you all kinds of headaches.

RegOpenKeyEx will return ERROR_SUCCESS if it finds the key. Just check against this constant and you are good to go.

这篇关于检查注册表项是否存在的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆