Registry.CreateSubKey什么时候返回null?

时间:2010-06-17 10:27:27

标签: c# registry

根据我在文档中的理解,如果失败则返回null,但在我看来,每个失败场景都有一个例外。

在什么标准情况下,此函数实际上会返回空值?

1 个答案:

答案 0 :(得分:1)

如果通过Reflector查看代码,您将看到如果从本机方法Win32Native.RegCreateKeyEx()返回的内容返回错误代码0以外的任何内容,或者操作结果是null然后它会将null返回给你。

此处可能出现的故障是,如果使用了不正确的权限,则会返回拒绝访问的错误代码。

此方法背后的代码如下:

[ComVisible(false)]
public unsafe RegistryKey CreateSubKey(string subkey, RegistryKeyPermissionCheck permissionCheck, RegistrySecurity registrySecurity)
{
    ValidateKeyName(subkey);
    ValidateKeyMode(permissionCheck);
    this.EnsureWriteable();
    subkey = FixupName(subkey);
    if (!this.remoteKey)
    {
        RegistryKey key = this.InternalOpenSubKey(subkey, permissionCheck != RegistryKeyPermissionCheck.ReadSubTree);
        if (key != null)
        {
            this.CheckSubKeyWritePermission(subkey);
            this.CheckSubTreePermission(subkey, permissionCheck);
            key.checkMode = permissionCheck;
            return key;
        }
    }
    this.CheckSubKeyCreatePermission(subkey);
    Win32Native.SECURITY_ATTRIBUTES structure = null;
    if (registrySecurity != null)
    {
        structure = new Win32Native.SECURITY_ATTRIBUTES();
        structure.nLength = Marshal.SizeOf(structure);
        byte[] securityDescriptorBinaryForm = registrySecurity.GetSecurityDescriptorBinaryForm();
        byte* pDest = stackalloc byte[1 * securityDescriptorBinaryForm.Length];
        Buffer.memcpy(securityDescriptorBinaryForm, 0, pDest, 0, securityDescriptorBinaryForm.Length);
        structure.pSecurityDescriptor = pDest;
    }
    int lpdwDisposition = 0;
    SafeRegistryHandle hkResult = null;
    int errorCode = Win32Native.RegCreateKeyEx(this.hkey, subkey, 0, null, 0, GetRegistryKeyAccess(permissionCheck != RegistryKeyPermissionCheck.ReadSubTree), structure, out hkResult, out lpdwDisposition);
    if ((errorCode == 0) && !hkResult.IsInvalid)
    {
        RegistryKey key2 = new RegistryKey(hkResult, permissionCheck != RegistryKeyPermissionCheck.ReadSubTree, false, this.remoteKey, false);
        this.CheckSubTreePermission(subkey, permissionCheck);
        key2.checkMode = permissionCheck;
        if (subkey.Length == 0)
        {
            key2.keyName = this.keyName;
            return key2;
        }
        key2.keyName = this.keyName + @"\" + subkey;
        return key2;
    }
    if (errorCode != 0)
    {
        this.Win32Error(errorCode, this.keyName + @"\" + subkey);
    }
    return null;
}