【问题标题】:kernel32.dll SetComputerName win32 error 6kernel32.dll SetComputerName win32 错误6
【发布时间】:2013-12-01 15:58:22
【问题描述】:

我尝试通过 kernel32.dll 导入和函数 SetComputerName 更改主机名。 SetComputerName function

主类:

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

导入类:

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

Marshal.GetLastWin32Error() 的结果是“6”。所以这意味着: ERROR_INVALID_HANDLE 6 (0x6) 句柄无效。

不知道手柄有什么问题。

【问题讨论】:

  • ms 描述为“句柄无效。”
  • SetComputerName():“如果函数成功,返回值是一个非零值”GetLastWin32Error() 的结果不必与您的 SetComputerName() 调用相关。函数调用返回了什么?
  • 当我设置SetLastError = true时,我以为win32错误中显示的最新错误?我在这里读到了一些问题,GetLastError 函数不是最好的。
  • 再次:SetComputerName() 调用返回了什么?
  • 现在可以了,问题出在函数定义上。现在我更改了 NetBios 名称,但我还想重命名主机名。更改注册表项 tcp/ip 的唯一方法是什么?

标签: c# runtime-error rename netbios


【解决方案1】:

你只是做错了。 SetComputerName() 的返回类型是 bool,而不是 int。当函数失败时返回 false。 winapi 中的硬性规则是,您应该只在函数失败时获取错误代码。或者换一种说法,当函数成功时,Windows 不会显式地将错误代码设置回 0。只有 然后 使用 Marshal.GetLastWin32Error() 来检索错误代码。否则由 Win32Exception 类构造函数自动完成。这使得这段代码工作:

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

【讨论】:

    猜你喜欢
    • 2018-05-29
    • 1970-01-01
    • 2015-10-12
    • 1970-01-01
    • 2020-03-18
    • 2010-11-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多