Search code examples
c#windowsenvironment-variablesregistry

Registry get directory owner programmatically using C#


I want to read programmatically the owner of a directory (and its subdirectories) of the windows registry using C#.

For example, assume my registry contains the directory HKEY_CURRENT_USER\Software\Microsoft which is owned by the user SYSTEM. A code example (leaving out the recursion over sub-directories of dir) how I intend to use it would be:

string dir = @"HKEY_CURRENT_USER\Software\Microsoft";
string owner = ReadRegOwner(dir); // owner is "SYSTEM"

However, I am not sure how to implement ReadRegOwner in C#. I have already found the RegistrySecurity class, but I am not sure how to use it to get the owner of a registry directory. It has the GetOwner member function, but that function requires an argument of type Type and I am not sure what to pass there.

Does anyone know how to implement this?


Solution

  • So, an implementation could look like:

    string ReadRegOwner(string dir)
    {
        RegistryKey key = Registry.CurrentUser.OpenSubKey(dir, false);
        RegistrySecurity rs = key.GetAccessControl();
        IdentityReference owner = rs.GetOwner(typeof(System.Security.Principal.NTAccount));
    
        return owner.ToString();
    }
    

    Example:

    string dir = @"Software\Microsoft";
    string owner = ReadRegOwner(dir); // Looks in HKEY_CURRENT_USER
    

    Of course, CurrentUser could be also replaced if a different base key than HKEY_CURRENT_USER is desired.