这是一个很好的链接,它详细讨论了它,并且除了本地计算机名称之外还处理活动目录成员身份和计算机命名。http://derrickswen.blogspot.com/2009/04/programmatically-renaming-computer.html http://derricksweng.blogspot.com/2009/04/programmatically-renaming-computer.html
(顺便说一句,如果您必须处理 Active Directory 命名,我会考虑使用计算机校长 http://msdn.microsoft.com/en-us/library/system.directoryservices.accountmanagement.computerprincipal.aspxSystem.DirectoryServices.AccountManagement 命名空间中的类,而不是博客文章中使用的 System.DirectoryServices 命名空间中的任何内容。)
调整了博客文章中的代码(您需要将对 System.Management 的引用添加到您的项目中):
public void RenameRemotePC(String oldName, String newName, String domain, NetworkCredential accountWithPermissions)
{
var remoteControlObject = new ManagementPath
{
ClassName = "Win32_ComputerSystem",
Server = oldName,
Path =
oldName + "\\root\\cimv2:Win32_ComputerSystem.Name='" + oldName + "'",
NamespacePath = "\\\\" + oldName + "\\root\\cimv2"
};
var conn = new ConnectionOptions
{
Authentication = AuthenticationLevel.PacketPrivacy,
Username = oldName + "\\" + accountWithPermissions.UserName,
Password = accountWithPermissions.Password
};
var remoteScope = new ManagementScope(remoteControlObject, conn);
var remoteSystem = new ManagementObject(remoteScope, remoteControlObject, null);
ManagementBaseObject newRemoteSystemName = remoteSystem.GetMethodParameters("Rename");
var methodOptions = new InvokeMethodOptions();
newRemoteSystemName.SetPropertyValue("Name", newName);
newRemoteSystemName.SetPropertyValue("UserName", accountWithPermissions.UserName);
newRemoteSystemName.SetPropertyValue("Password", accountWithPermissions.Password);
methodOptions.Timeout = new TimeSpan(0, 10, 0);
ManagementBaseObject outParams = remoteSystem.InvokeMethod("Rename", newRemoteSystemName, null);
}