我正在尝试从 C# 应用程序重命名计算机名称。
public class ComputerSystem : IComputerSystem
{
private readonly ManagementObject computerSystemObject;
public ComputerSystem()
{
var computerPath = string.Format("Win32_ComputerSystem.Name='{0}'", Environment.MachineName);
computerSystemObject = new ManagementObject(new ManagementPath(computerPath));
}
public bool Rename(string newComputerName)
{
var result = false;
var renameParameters = computerSystemObject.GetMethodParameters("Rename");
renameParameters["Name"] = newComputerName;
var output = computerSystemObject.InvokeMethod("Rename", renameParameters, null);
if (output != null)
{
var returnValue = (uint)Convert.ChangeType(output.Properties["ReturnValue"].Value, typeof(uint));
result = returnValue == 0;
}
return result;
}
}
WMI 调用返回错误代码 1355。
MSDN 没有提到太多关于错误代码的信息,它是什么意思以及如何修复它?
错误代码 1355 表示ERROR_NO_SUCH_DOMAIN
:"指定的域不存在或无法联系。
重命名方法的文档指出,名称必须包含域名。对于未加入域的计算机,请尝试.NewName
,而不仅仅是NewName
。
由于系统的保护,使用任何外部方法更新PC名称都非常困难。最好的方法是使用WMIC的Windows自己的实用程序.exe重命名PC。只需从 C# 启动 wmic.exe 并将重命名命令作为参数传递即可。
退出代码 0
>
public void SetMachineName(string newName)
{
// Create a new process
ProcessStartInfo process = new ProcessStartInfo();
// set name of process to "WMIC.exe"
process.FileName = "WMIC.exe";
// pass rename PC command as argument
process.Arguments = "computersystem where caption='" + System.Environment.MachineName + "' rename " + newName;
// Run the external process & wait for it to finish
using (Process proc = Process.Start(process))
{
proc.WaitForExit();
// print the status of command
Console.WriteLine("Exit code = " + proc.ExitCode);
}
}