在C#中更改本地管理员密码 [英] Change local administrator password in C#

查看:532
本文介绍了在C#中更改本地管理员密码的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我要寻找一种方式来在Windows更改本地用户帐户(本地管理员)的密码(XP在这种情况下)的机器。我已阅读 $ C $的CProject文章了解一种方式来做到这一点,不过这似乎并不干净。

我可以看到,这是可能的WMI 做的,所以这可能是答案,但我无法弄清楚如何使用WinNT WMI命名空间的ManagementObject。当我尝试以下code,它抛出一个无效参数的异常。

 公共静态无效ResetPassword(字符串计算机名,用户名字符串,字符串NEWPASSWORD){
            的ManagementObject的ManagementObject =新的ManagementObject(WINNT://+计算机名+/+用户名); //抛出异常
            [对象] newpasswordObj = {}新密码;
            managementObject.InvokeMethod(SetPassword,newpasswordObj);
}

有没有更好的方法来做到这一点? (我使用.NET 3.5)

编辑:感谢伊利指着我在正确的方向。这里是code我最终使用:

 公共静态无效ResetPassword(字符串计算机名,用户名字符串,字符串NEWPASSWORD){
        的DirectoryEntry的DirectoryEntry =新的DirectoryEntry(的String.Format(WINNT:// {0} / {1},计算机名,用户名));
        directoryEntry.Invoke(SetPassword新密码);
}


解决方案

尝试的DirectoryEntry 类,而不是的ManagementObject 类。

I am looking for a way to change the password of a local user account (local Administrator) on a Windows (XP in this case) machine. I have read the CodeProject article about one way to do this, but this just doesn't seem 'clean'.

I can see that this is possible to do with WMI, so that might be the answer, but I can't figure out how to use the WinNT WMI namespace with ManagementObject. When I try the following code it throws an "Invalid Parameter" exception.

public static void ResetPassword(string computerName, string username, string newPassword){ 
            ManagementObject managementObject = new ManagementObject("WinNT://" + computerName + "/" + username); // Throws Exception
            object[] newpasswordObj = {newPassword};
            managementObject.InvokeMethod("SetPassword", newpasswordObj);
}

Is there a better way to do this? (I'm using .NET 3.5)

Edit: Thanks Ely for pointing me in the right direction. Here is the code I ended up using:

public static void ResetPassword(string computerName, string username, string newPassword) { 
        DirectoryEntry directoryEntry = new DirectoryEntry(string.Format("WinNT://{0}/{1}", computerName, username)); 
        directoryEntry.Invoke("SetPassword", newPassword);
}

解决方案

Try the DirectoryEntry class instead of ManagementObject class.

这篇关于在C#中更改本地管理员密码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆