Question

I try to change the hostname via kernel32.dll import and the function SetComputerName. SetComputerName function

Mainclass:

namespace Castell
{
  class Program
  {
      private static string hostname { get; set; }
      setHostname();
      private static void setHostname()
      {
         hostname = "TEST123456789";
         int errorcode = ImportDLL.SetComputerName(hostname);
         Console.WriteLine(Marshal.GetLastWin32Error());
      }
  }
}

Import Class:

namespace Castell
{
    class ImportDLL
    {
        [DllImport("Kernel32.dll", CharSet = CharSet.Auto, SetLastError = true)]
        public static extern int SetComputerName(string hostname);
    }
}

Result of the Marshal.GetLastWin32Error() is "6". So that means: ERROR_INVALID_HANDLE 6 (0x6) The handle is invalid.

Dont know whats wrong with the handle.

Was it helpful?

Solution

You are just doing it wrong. The return type of SetComputerName() is bool, not int. It returns false when the function failed. The hard rule in the winapi is that you should only ever obtain the error code when the function failed. Or to put it another way, Windows doesn't explicitly set the error code back to 0 when the function is successful. Only then use Marshal.GetLastWin32Error() to retrieve the error code. Otherwise done automatically by the Win32Exception class constructor. Which makes this code work:

  public static void SetHostname(string hostname)
  {
     if (!SetComputerName(hostname)) {
         throw new System.ComponentModel.Win32Exception();
     }
  }

  [DllImport("Kernel32.dll", CharSet = CharSet.Auto, SetLastError = true)]
  private static extern int SetComputerName(string hostname);
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top