5
votes

I am working now on some stuff regarding registry.

I checked the enum RegistryRights in System.Security.AccessControl.

public enum RegistryRights
{
    QueryValues = 1,
    SetValue = 2,
    CreateSubKey = 4,
    EnumerateSubKeys = 8,
    Notify = 16,
    CreateLink = 32,
    Delete = 65536,
    ReadPermissions = 131072,
    WriteKey = 131078,
    ExecuteKey = 131097,
    ReadKey = 131097,
    ChangePermissions = 262144,
    TakeOwnership = 524288,
    FullControl = 983103,
}

This enum is a bitwise,And I know that enums can contains duplicate values. I was trying to iterate through the enum by this code:

 foreach (System.Security.AccessControl.RegistryRights regItem in Enum.GetValues(typeof(System.Security.AccessControl.RegistryRights)))
        {
            System.Diagnostics.Debug.WriteLine(regItem.ToString() + "  " + ((int)regItem).ToString());
        }

also Enum.GetName(typeof(RegistryRights),regItem) return the same key name.

and the output I got is:


QueryValues  1
SetValue  2
CreateSubKey  4
EnumerateSubKeys  8
Notify  16
CreateLink  32
Delete  65536
ReadPermissions  131072
WriteKey  131078
ReadKey  131097
ReadKey  131097
ChangePermissions  262144
TakeOwnership  524288
FullControl  983103

Can someone please tell me why do I get duplicate keys?("ReadKey" instead of "ExecuteKey") How can I force it to cast the int to the second key of the value ? and why ToString does not return the real key value?

2

2 Answers

4
votes

I think you would have to iterate over the enum Names rather than values. Something like:

foreach (string regItem in Enum.GetNames(typeof(RegistryRights)))
{
    var value = Enum.Parse(typeof(RegistryRights), regItem);

    System.Diagnostics.Debug.WriteLine(regItem + "  " + ((int)value).ToString());
}

As to why this happens, there's no way for the runtime to know which name to return if the values are duplicate. This is why iterating through the names (which are guaranteed to be unique) produces the results you're looking for.

3
votes

Note that both ReadKey and ExecuteKey have same values defined which equals 131097.

ExecuteKey = 131097,
ReadKey = 131097,

So technically both are equal.