0

I am trying to change the ComputerName on a windows machine. I am having a very strange result.

The Code that I'm using is:

public class MachineService
{
      [DllImport("Kernel32.dll")]
      [return: MarshalAs(UnmanagedType.Bool)]
      private static extern bool SetComputerNameA([MarshalAs(UnmanagedType.LPStr)] string computerName);

      [DllImport("Kernel32.dll")]
      [return: MarshalAs(UnmanagedType.Bool)]
      private static extern bool SetComputerName([MarshalAs(UnmanagedType.LPStr)] string computerName);

      [DllImport("Kernel32.dll")]
      [return: MarshalAs(UnmanagedType.Bool)]
      private static extern bool SetComputerNameEx(ComputerNameFormat NameType, [MarshalAs(UnmanagedType.LPStr)] string computerName);


    public static bool ChangeName(string name)
    {
      var envVar = SetComputerName(name);
      var ex = SetComputerNameEx(ComputerNameFormat.ComputerNamePhysicalNetBIOS, name);
      return envVar && ex;
    }
}

It does set the Environmental Variable ComputerName but it doesn't set the name of the device. please see the images below.

PowerShell ComputerName

System Name

EDIT It has changed the registry.

RegEdit

3xGuy
  • 2,235
  • 2
  • 29
  • 51
  • Even after a restart? – canton7 Jun 16 '20 at 15:15
  • 1
    yes, I restart and it doesn't change – 3xGuy Jun 16 '20 at 15:16
  • Does this answer your question? [SetComputerNameEX returns success but computer name not changed upon restart](https://stackoverflow.com/questions/48506437/setcomputernameex-returns-success-but-computer-name-not-changed-upon-restart) – Sorceri Jun 16 '20 at 17:19
  • If I read the [documentation](https://learn.microsoft.com/en-us/windows/win32/api/sysinfoapi/nf-sysinfoapi-setcomputernameexw) correctly you should be using `ComputerNamePhysicalDnsHostname` instead of `ComputerNamePhysicalNetBIOS`, and you should NOT call `SetComputerName` before `SetComputerNameEx`. – Sam Axe Jun 16 '20 at 17:24
  • @SamAxe That was the issue. if you add an answer to it I will vote it up. THANK YOU! – 3xGuy Jun 16 '20 at 17:45
  • Glad it helped. – Sam Axe Jun 16 '20 at 17:52

1 Answers1

1

If I read the documentation correctly you should:

  • be using ComputerNamePhysicalDnsHostname instead of ComputerNamePhysicalNetBIOS
  • and you should NOT call SetComputerName before SetComputerNameEx
Sam Axe
  • 33,313
  • 9
  • 55
  • 89