重命名计算机programmaticaly C#.NET重命名、计算机、NET、programmaticaly

2023-09-04 09:07:34 作者:ご噬魂★魅影﹌

我需要通过.NET应用程序来重命名我的电脑。 我曾尝试code:

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

和我已经试过这样:

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

我不知道如何得到它的工作....

i don't know how to get it work....

感谢你。

推荐答案

我已经尝试了所有我所发现的更改计算机名的方式,没有一部作品.....它不更改计算机名... 它的工作的唯一办法是,当我chaged一些注册表键值,这是code,它是确定这样做呢?

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