Search code examples
c#.net-coreunmanaged

Not Changing Computer Name, but changing $env:ComputerName


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


Solution

  • If I read the documentation correctly you should:

    • be using ComputerNamePhysicalDnsHostname instead of ComputerNamePhysicalNetBIOS
    • and you should NOT call SetComputerName before SetComputerNameEx