Search code examples
c#.net.net-2.0hostnamecomputer-name

How can one change a Windows 2000 computer name in .NET 2.0?


I'm trying to change a computer's name (host name) on Windows 2000 using .NET 2.0. The computer is not joined to a domain.

Windows XP and higher provides the WMI method Win32_ComputerSystem.Rename, but this is not available in Windows 2000 (reference here).

I'm not averse to just calling an external program if I need to, but I also can't seem to find one that works on Windows 2000. Searching on Google didn't seem to turn up anything obvious.

Thanks in advance.


Solution

  • I think the Windows API might be of help on Windows 2000: Use SetComputerNameEx:

    BOOL WINAPI SetComputerNameEx(
      __in  COMPUTER_NAME_FORMAT NameType,
      __in  LPCTSTR lpBuffer
    );
    

    This sample is based on the sample on pinvoke.net:

    public class RenameComputer
    {
        [DllImport("kernel32.dll", CharSet = CharSet.Auto)]
        static extern bool SetComputerNameEx(COMPUTER_NAME_FORMAT NameType, string lpBuffer);
    
        enum COMPUTER_NAME_FORMAT
        {
            ComputerNameNetBIOS,
            ComputerNameDnsHostname,
            ComputerNameDnsDomain,
            ComputerNameDnsFullyQualified,
            ComputerNamePhysicalNetBIOS,
            ComputerNamePhysicalDnsHostname,
            ComputerNamePhysicalDnsDomain,
            ComputerNamePhysicalDnsFullyQualified,
        }
    
        //ComputerNamePhysicalDnsHostname used to rename the computer name and netbios name before domain join
        public static bool Rename(string name)
        {
            bool result = SetComputerNameEx(COMPUTER_NAME_FORMAT.ComputerNamePhysicalDnsHostname, name);
            if (!result)
                throw new Win32Exception();
    
            return result;
        }
    }
    

    In addition to p-invoking the WinAPI you might also use Process.Start in combination with the netsh command as described here.