我正在尝试TRegistry
使用Delphi中的组件将值写入 HKLM 注册表。
由于我作为标准用户在 Windows 2000 上运行(或作为标准用户的 XP,或作为标准用户的 Windows Vista,或带有标准用户的 Windows 7),我完全希望我将无法写入该HKEY_LOCAL_MACHINE
部分注册表:
reg := TRegistry.Create(KEY_WRITE);
try
reg.Access := KEY_WRITE; //sure, set it again, why not
reg.RootKey := HKEY_LOCAL_MACHINE;
if not reg.OpenKey('\Software\Microsoft\SQMClient', True) then
Exit;
reg.WriteString('MachineId', s);
finally
reg.Free;
end;
不幸的是,WriteString
抛出一个ERegistryException
:
Failed to set data for 'MachineId`
这是完全可以预料的,这就是我试图避免异常的原因。我没有看到任何CanWriteString
或TryWriteString
在TRegistry
.
尝试写入 HKLM 时如何不触发异常?
不言自明的注意事项:
- 如果用户实际上是管理员,那么写入应该能够成功
将调用包装
WriteString
在 try-except 中:reg := TRegistry.Create(KEY_WRITE); try reg.RootKey := HKEY_LOCAL_MACHINE; if not reg.OpenKey('\Software\Microsoft\SQMClient', True) then Exit; try reg.WriteString('MachineId', s); except on E:ERegistryException do {nothing}; end; finally reg.Free; end;
不会阻止首先抛出异常。
更新:来自 RTL 来源:
KEY_WRITE = (STANDARD_RIGHTS_WRITE or
KEY_SET_VALUE or
KEY_CREATE_SUB_KEY) and not
SYNCHRONIZE;
来自MSDN:
KEY_WRITE (0x20006)
结合了 STANDARD_RIGHTS_WRITE、KEY_SET_VALUE 和 KEY_CREATE_SUB_KEY 访问权限。