I have already done some Googling to see if I could find a solution, but so far I haven't found anything useful. My problem is exactly as the title states. I try to log a remote machine on as a specified user by changing registry values, and it works fine in debug mode, but not release (registry values remain the same). I'm logged into Windows as an admin, and I also use my admin credentials for WMI. The return value is "0" for both cases, which implies there's no error. Another thing to note is that all my other functions that use WMI work fine in both debug and release versions (i.e. WMI queries, WMI Shutdown/Restart/Logoff), so I'm not sure why this specific one won't work in release mode. Here's my code:
public static bool LogOnAsViaWMI(string computerName, string username, string password, string logonUsername, string logonPW)
{
try
{
// Set connection options
ConnectionOptions options = new ConnectionOptions();
options.EnablePrivileges = true;
options.Username = username;
options.Password = password;
// Connect to machine
ManagementScope scope = new ManagementScope("\\\\" + computerName + "\\root\\CIMV2", options);
scope.Connect();
// Set management class
ManagementPath managementPath = new ManagementPath("StdRegProv");
ManagementClass mc = new ManagementClass(scope, managementPath, null);
// Set registry values
if (!SetRegKeyValue(mc, "AutoAdminLogon", "1") ||
!SetRegKeyValue(mc, "ForceAutoLogon", "1") ||
!SetRegKeyValue(mc, "DefaultUserName", logonUsername) ||
!SetRegKeyValue(mc, "DefaultPassword", logonPW) ||
!SetRegKeyValue(mc, "DefaultDomainName", "MyDomainName"))
{
MessageBox.Show("Failed to set Windows logon registry values");
return false;
}
// Log off to log in as new default
LogOff(computerName, username, password);
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
return true;
}
private static bool SetRegKeyValue(ManagementClass mc, string valueName, string value)
{
// Set values
ManagementBaseObject inParams = mc.GetMethodParameters("SetStringValue");
inParams["hDefKey"] = HKEY_LOCAL_MACHINE;
inParams["sSubKeyName"] = @"SOFTWARE\Microsoft\Windows NT\CurrentVersion\Winlogon";
inParams["sValueName"] = valueName;
inParams["sValue"] = value;
// Invoke inParams
ManagementBaseObject outParams = mc.InvokeMethod("SetStringValue", inParams, null);
if (outParams["returnValue"].ToString() != "0")
return false;
return true;
}