2011-10-04 24 views
8

Devo rinominare il mio computer tramite l'applicazione .net. Ho provato questo codice:rinominare il computer a livello di programmazione 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; 
     } 
    } 
} 

ma non ha funzionato.

e ho provato questo:

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

ma anche non ha funzionato.

+4

"non ha funzionato" si intende .... errori? – Shoban

+0

Devi riavviare il computer per riflettere realmente le modifiche? O hai qualche errore? –

+0

@ Olia Cambiare il nome del computer tramite applicazioni di terze parti, se possibile, causerà un sacco di problemi. – Mob

risposta

6

Ho provato tutti i modi che ho trovato per cambiare del computer nome e nessuno funziona ..... non cambia il nome del computer ... l'unico modo in cui ha funzionato è quando ho scartato alcuni valori di chiave del Registro di sistema, questo è il codice, è giusto farlo?

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

e dopo il riavvio il nome cambia ....

3

Dalla documentazione MSDN di SetComputerName ..

stabilisce un nuovo nome NetBIOS per il computer locale. Il nome viene memorizzato nel registro e la modifica del nome ha effetto la volta successiva che l'utente riavvia il computer.

Hai provato a riavviare il computer?

+0

sì ... ho riavviato –

1

Programmatically renaming a computer using C#

Si tratta di un lungo articolo e non sono sicuro di cosa esattamente sarà direttamente rilevanti quindi non mi incollare un frammento

+3

Mentre questo può teoricamente rispondere alla domanda, [sarebbe preferibile] (http: //meta.stackexchange.it/q/8259) per includere qui le parti essenziali della risposta e fornire il link per riferimento. –

+0

la funzione in questo articolo, che modifica il nome del computer, genera questa eccezione: il percorso di rete non è stato trovato. (Eccezione da HRESULT: 0x80070035) –

2

oggetti WMI A imposta il nome del computer. Quindi il registro viene utilizzato per verificare se il nome è stato impostato. Perché System.Environment.MachineName non viene aggiornato immediatamente. E il comando "hostname" in CMD.exe restituisce ancora il vecchio nome. Quindi è ancora necessario il riavvio. Ma con il controllo del registro puoi vedere se il nome è stato impostato.

Spero che questo aiuti.

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

È molto difficile da aggiornare nome PC utilizzando qualsiasi metodo esterni grazie alla protezione del sistema. Il modo migliore per farlo è utilizzare l'utilità Windows di WMIC.exe per rinominare il PC. Basta avviare wmic.exe da C# e passare il comando rename come argomento.

>

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

Qual è la tua domanda? Quale sembra essere il problema specifico che stai avendo? – TVOHM