Search code examples
c#wmi

Rename computer name with .NET


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?


Solution

  • 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.