开发者

Access remote registry key with C# in .Net MVC2

开发者 https://www.devze.com 2023-01-15 04:37 出处:网络
I\'m using the following code private static string GetLogonFromMachine(string machine) { //1. To read the registry key that stores this value.

I'm using the following code

private static string GetLogonFromMachine(string machine)
{
    //1. To read the registry key that stores this value. 
    //HKEY_Local_Machine\Software\Microsoft\Windows NT\CurrentVersion\WinLogon\DefaultUserName

    var rHive = RegistryKey.OpenRemoteBaseKey(RegistryHive.LocalMachine, machine);

    var rKey = rHive.OpenSubKey(@"Software\Microsoft\Windows NT\CurrentVersion\WinLogon");

    var rItem = rKey.GetValue("DefaultUserName");
    return rItem.ToString();
}

and I've confirmed that my user has access, the M开发者_如何转开发VC site is using integrated authentication and that the listed REG_SZ "DefaultUserName" has a value on the machine targetted but rItem doesn't grab a value.

I guess I'm doing something silly and I'd love to know what!


I was indeed being silly. I wasn't sorting the list of machine names before use and so I was looking at the registry of the wrong machine. The machine that was actually in focus was correctly returning "".

I've ended up with

        private static string GetLogonFromMachine(string machine)
    {
        //1. To read the registry key that stores this value. 
        //HKEY_Local_Machine\Software\Microsoft\Windows NT\CurrentVersion\WinLogon\DefaultUserName

        RegistryKey rHive;

        try
        {
            rHive = RegistryKey.OpenRemoteBaseKey(RegistryHive.LocalMachine, machine);
        }
        catch (IOException)
        {
            return "offline";
        }

        var rKey = rHive.OpenSubKey("Software\\Microsoft\\Windows NT\\CurrentVersion\\WinLogon\\");

        if (rKey == null)
        {
            return "No Logon Found";
        }

        var rItem = rKey.GetValue("DefaultUserName");

        return rItem==null ? "No Logon Found" : rItem.ToString();
    }
0

精彩评论

暂无评论...
验证码 换一张
取 消