rename computer programmatically c# .net

2019-01-27 17:57发布

问题:

I need to rename my computer via .net application. I have tried this code:

public static bool SetMachineName(string newName)
{
    MessageBox.Show(String.Format("Setting Machine Name to '{0}'...", newName));

    // Invoke WMI to populate the machine name
    using (ManagementObject wmiObject = new ManagementObject(new ManagementPath(String.Format("Win32_ComputerSystem.Name='{0}'",System.Environment.MachineName))))
    {
        ManagementBaseObject inputArgs = wmiObject.GetMethodParameters("Rename");
        inputArgs["Name"] = newName;

        // Set the name
        ManagementBaseObject outParams = wmiObject.InvokeMethod("Rename",inputArgs,null);

        uint ret = (uint)(outParams.Properties["ReturnValue"].Value);
        if (ret == 0)
        {
            //worked
            return true;
        }
        else
        {
            //didn't work
            return false;
        }
    }
}

but it didn't work.

and i have tried this one:

using System.Runtime.InteropServices;

[DllImport("kernel32.dll")]
static extern bool SetComputerName(string lpComputerName);

public static bool SetMachineName(string newName)
{

    bool done = SetComputerName(newName);
    if (done)
    {
        { MessageBox.Show("Done"); return true; }
    }
    else
    { MessageBox.Show("Failed"); return false; }
}

but it also didn't work.

回答1:

I have tried all the ways i have found to change computer name and no one works.....it doesn't change the computer name... the only way it worked is when i chaged some registry key values , this is the code , is it ok to do so?

public static bool SetMachineName(string newName)
{
    RegistryKey key = Registry.LocalMachine;

    string activeComputerName = "SYSTEM\\CurrentControlSet\\Control\\ComputerName\\ActiveComputerName";
    RegistryKey activeCmpName = key.CreateSubKey(activeComputerName);
    activeCmpName.SetValue("ComputerName", newName);
    activeCmpName.Close();
    string computerName = "SYSTEM\\CurrentControlSet\\Control\\ComputerName\\ComputerName";
    RegistryKey cmpName = key.CreateSubKey(computerName);
    cmpName.SetValue("ComputerName", newName);
    cmpName.Close();
    string _hostName = "SYSTEM\\CurrentControlSet\\services\\Tcpip\\Parameters\\";
    RegistryKey hostName = key.CreateSubKey(_hostName);
    hostName.SetValue("Hostname",newName);
    hostName.SetValue("NV Hostname",newName);
    hostName.Close();
    return true;
}

and after the restart the name changes....



回答2:

From the MSDN Documentation of SetComputerName..

Sets a new NetBIOS name for the local computer. The name is stored in the registry and the name change takes effect the next time the user restarts the computer.

Did you try restarting the computer?



回答3:

A WMI objects sets the computer name. Then the registry is used to check whether the name was set. Because the System.Environment.MachineName is not updated right away. And the 'hostname' command in CMD.exe still outputs the old name. So a reboot is still required. But with the registry check can see if the name was set.

Hope this helps.

Boolean SetComputerName(String Name)  
{  
String RegLocComputerName = @"SYSTEM\CurrentControlSet\Control\ComputerName\ComputerName";
try
{
    string compPath= "Win32_ComputerSystem.Name='" + System.Environment.MachineName + "'";
    using (ManagementObject mo = new ManagementObject(new ManagementPath(compPath)))
    {
        ManagementBaseObject inputArgs = mo.GetMethodParameters("Rename");
        inputArgs["Name"] = Name;
        ManagementBaseObject output = mo.InvokeMethod("Rename", inputArgs, null);
        uint retValue = (uint)Convert.ChangeType(output.Properties["ReturnValue"].Value, typeof(uint));
        if (retValue != 0)
        {
            throw new Exception("Computer could not be changed due to unknown reason.");
        }
    }

    RegistryKey ComputerName = Registry.LocalMachine.OpenSubKey(RegLocComputerName);
    if (ComputerName == null)
    {
        throw new Exception("Registry location '" + RegLocComputerName + "' is not readable.");
    }
    if (((String)ComputerName.GetValue("ComputerName")) != Name)
    {
        throw new Exception("The computer name was set by WMI but was not updated in the registry location: '" + RegLocComputerName + "'");
    }
    ComputerName.Close();
    ComputerName.Dispose();
}
catch (Exception ex)
{
    return false;
}
return true;  
}


回答4:

Programmatically renaming a computer using C#

It is a long article and I'm not sure what exactly will be directly relevant so I won't paste a snippet