12

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.

5
  • 4
    "Did not work" means.... errors? Commented Oct 4, 2011 at 10:46
  • Do you have to restart the computer to really reflect the changes? Or do you get some errors? Commented Oct 4, 2011 at 10:47
  • @Olia Changing the computer name via third party apps, if possible, is going to cause a whole lot of problems. Commented Oct 4, 2011 at 10:48
  • the code is working with no exceptions in the second way , but after the restart the name doesn't change.... in the first way the ret value is != 0 and I get false --> didn't work... Commented Oct 4, 2011 at 10:54
  • when i rename the computer name in the second way , it doesn't change in the properties of MyComuter , but when i get computer name in .net , i see the new name(changed name...), how can it be ? Commented Oct 4, 2011 at 11:48

4 Answers 4

13

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

Sign up to request clarification or add additional context in comments.

1 Comment

Please remember pc name limit to 15 characters. Otherwise, your pc will be crashed.
4

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

Comments

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?

Comments

0

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

2 Comments

While this may theoretically answer the question, it would be preferable to include the essential parts of the answer here, and provide the link for reference.
the function in this article , which changes the name of the computer , throws this exception - The network path was not found. (Exception from HRESULT: 0x80070035)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.