C# 修改本地管理员密码
我正在寻找一种方法来更改 Windows(本例中为 XP)计算机上的本地用户帐户(本地管理员)的密码。 我已阅读 CodeProject 文章 关于实现此目的的一种方法,但这看起来并不“干净”。
我可以看到这可能与WMI有关 ,所以这可能是答案,但我不知道如何将 WinNT WMI 命名空间与 ManagementObject 一起使用。 当我尝试以下代码时,它会抛出“无效参数”异常。
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);
}
有一个更好的方法吗? (我正在使用 .NET 3.5)
编辑:感谢 Ely 为我指明了正确的方向。 这是我最终使用的代码:
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);
}
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);
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
尝试使用
DirectoryEntry
类而不是ManagementObject
类。Try the
DirectoryEntry
class instead ofManagementObject
class.正如 Ely 指出的,您可以根据 MSDN 使用 System.DirectoryServices 代码来完成此操作:
As Ely noted, you can use the System.DirectoryServices code to accomplish this per MSDN: