用.NET重命名计算机名称

时间:2015-04-25 15:04:40

标签: c# wmi

我正在尝试从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并未提及错误代码,它的含义是什么以及如何解决?

2 个答案:

答案 0 :(得分:4)

Error code 1355表示ERROR_NO_SUCH_DOMAIN"指定的域名不存在或无法联系。"

documentation for the Rename method表示名称必须包含域名。对于未加入域的计算机,请尝试.\NewName,而不仅仅是NewName

答案 1 :(得分:0)

由于系统的保护,使用任何外部方法更新PC名称非常困难。最好的方法是使用Windows自带的WMIC.exe实用程序重命名PC。只需从C#启动wmic.exe并将rename命令作为参数传递。

退出代码0

>

{{1}}
相关问题