Rename computer name with .NET

2019-07-18 16:11发布

问题:

I am trying to rename a computer name from a C# application.

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;
    }
}

The WMI call returns error code 1355.

MSDN doesn't mention much about error codes, what does it mean and how can I fix it?

回答1:

Error code 1355 means ERROR_NO_SUCH_DOMAIN: "The specified domain either does not exist or could not be contacted.".

The documentation for the Rename method states that the name must contain the domain name. For a non-domain-joined machine, try .\NewName instead of just NewName.



回答2:

It's very difficult to update the PC name using any external methods due to protection of the system. The best way to do so is to use the Windows own utility of WMIC.exe to rename the PC. Just launch the wmic.exe from C# and pass rename command as argument.

exit code 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);
    }
}


标签: c# wmi