rename computer programmatically c# .net
Asked Answered
K

4

11

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.

Knife answered 4/10, 2011 at 10:44 Comment(5)
"Did not work" means.... errors?Hogback
Do you have to restart the computer to really reflect the changes? Or do you get some errors?Calloway
@Olia Changing the computer name via third party apps, if possible, is going to cause a whole lot of problems.Beatriz
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...Knife
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 ?Knife
K
12

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

Knife answered 5/10, 2011 at 12:31 Comment(0)
A
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;  
}
Anastasio answered 17/9, 2012 at 7:52 Comment(0)
D
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?

Domella answered 4/10, 2011 at 10:48 Comment(0)
T
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

Tonnie answered 4/10, 2011 at 10:48 Comment(2)
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.Lilliamlillian
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)Knife

© 2022 - 2024 — McMap. All rights reserved.