且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何检查是否允许用户读取/写入特定的注册表项?

更新时间:2022-11-01 09:41:55

RegistryPermission 类控制reg密钥周围的安全权限.要检查您是否具有对权限的写权限,请按以下方式使用它:

The RegistryPermission class governs the security permissions around reg keys. To check if you may have write access to a permission you use it in the following manner:

RegistryPermission perm1 = new RegistryPermission(RegistryPermissionAccess.Write, @"SOFTWARE\Microsoft\Windows\CurrentVersion\Run");

然后,您将在try/catch中使用"Demand"方法,并在失败(引发安全异常)时返回.成功后,您将继续执行更新.尽管这并不是您想要的,但要在访问之前先检查权限,这是一种公认​​的方式,可确保您拥有对按键进行操作之前所需的权限.以完全结构化的方式,这相当于:

You would then use the "Demand" method in a try/catch and return on failure (the raising of a security exception). On success you'd carry on and perform your update. Although this isn't quite what you want, a check on permissions before access, it is the accepted way of ensuring you have the permissions you need before you operate on the keys. In a fully structured manner this would equate to:

try
{
    RegistryPermission perm1 = new RegistryPermission(RegistryPermissionAccess.Write, @"SOFTWARE\Microsoft\Windows\CurrentVersion\Run");
    perm1.Demand();
}
catch (System.Security.SecurityException ex)
{
    return;
}

//Do your reg updates here

编辑:考虑到我在评论中提到的内容,这是用于权限检查的RegistryPermission类的扩展方法:

Thinking on what I mentioned in the comment, here are extension methods to the RegistryPermission class for permission checks:

using System.Security.Permissions;
using System.Security;

public static class RegistryExtensions
{
    public static bool HavePermissionsOnKey(this RegistryPermission reg, RegistryPermissionAccess accessLevel, string key)
    {
        try
        {
            RegistryPermission r = new RegistryPermission(accessLevel, key);
            r.Demand();
            return true;
        }
        catch (SecurityException)
        {
            return false;
        }
    }

    public static bool CanWriteKey(this RegistryPermission reg, string key)
    {
        try
        {
            RegistryPermission r = new RegistryPermission(RegistryPermissionAccess.Write, key);
            r.Demand();
            return true;
        }
        catch (SecurityException)
        {
            return false;
        }
    }

    public static bool CanReadKey(this RegistryPermission reg, string key)
    {
        try
        {
            RegistryPermission r = new RegistryPermission(RegistryPermissionAccess.Read, key);
            r.Demand();
            return true;
        }
        catch (SecurityException)
        {
            return false;
        }
    }
}