2011-10-04 18 views
8

Necesito cambiar el nombre de mi computadora a través de la aplicación .net. He probado este código:cambiar el nombre de la computadora mediante programación C# .net

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

pero no funcionó.

y he tratado de éste:

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

pero también no funcionaba.

+4

"no funcionó" significa .... errores? – Shoban

+0

¿Tiene que reiniciar la computadora para reflejar realmente los cambios? ¿O recibes algunos errores? –

+0

@Olia Cambiar el nombre de la computadora a través de aplicaciones de terceros, si es posible, va a causar un montón de problemas. – Mob

Respuesta

6

He intentado todas las maneras que he encontrado para cambiar de ordenador nombre y nadie funciona ... no cambia el nombre de la computadora ... la única forma en que funcionó es cuando clasifiqué algunos valores clave de registro, este es el código, ¿está bien hacerlo?

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

y después de la reanudación el nombre cambia ....

3

de la documentación de MSDN de SetComputerName ..

establece un nuevo nombre de NetBIOS para el equipo local. El nombre se almacena en el registro y el cambio de nombre entra en vigencia la próxima vez que el usuario reinicie la computadora.

¿Intentó reiniciar la computadora?

+0

sí ... reinicié –

1

Programmatically renaming a computer using C#

Es un artículo largo y no estoy seguro de qué es exactamente será directamente relevante por lo que no voy a pegar un fragmento

+3

Si bien esto puede responder teóricamente a la pregunta, [sería preferible] (http: //meta.stackexchange.com/q/8259) para incluir las partes esenciales de la respuesta aquí y proporcionar el enlace para referencia. –

+0

la función de este artículo, que cambia el nombre de la computadora, arroja esta excepción: no se encontró la ruta de la red. (Excepción de HRESULT: 0x80070035) –

2

objetos Una WMI establece el nombre del equipo. Luego, el registro se usa para verificar si el nombre fue establecido. Porque System.Environment.MachineName no se actualiza de inmediato. Y el comando 'hostname' en CMD.exe todavía muestra el nombre anterior. Por lo tanto, todavía se requiere reiniciar. Pero con la verificación de registro puede ver si el nombre fue establecido.

Espero que esto ayude.

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

Es muy difícil actualizar el nombre de la PC utilizando métodos externos debido a la protección del sistema. La mejor manera de hacerlo es usar la utilidad propia de WMIC.exe para cambiar el nombre de la PC. Simplemente inicie wmic.exe desde C# y pase el comando rename como argumento.

>

public void SetMachineName(string newName) 
{ 

    // Create a new process 
    ProcessStartInfo process = new ProcessStartInfo(); 

    // set name of process to "WMIC.exe" 
    process.FileName = "WMIC.exe"; 

    // pass rename PC command as argument 
    process.Arguments = "computersystem where caption='" + System.Environment.MachineName + "' rename " + newName; 

    // Run the external process & wait for it to finish 
    using (Process proc = Process.Start(process)) 
    { 
     proc.WaitForExit(); 

     // print the status of command 
     Console.WriteLine("Exit code = " + proc.ExitCode); 
    } 
} 
+0

¿Cuál es su pregunta? ¿Cuál parece ser el problema específico que estás teniendo? – TVOHM

Cuestiones relacionadas