使用VB.net更改计算机名

使用VB.net更改计算机名,vb.net,Vb.net,我正在尝试使用以下代码更改带有VB.net的PC的计算机名: Declare Auto Function SetComputerName Lib "kernel32" (ByVal lpComputerName As String) As Integer computerName = "Testing" SetComputerName(computerName.ToString) 是这样吗?因为它不会更改计算机名 非常感谢您的帮助。我以前通过让我的vb.net代码生成一个bat文件

我正在尝试使用以下代码更改带有VB.net的PC的计算机名:

Declare Auto Function SetComputerName Lib "kernel32" (ByVal lpComputerName As String) As Integer

computerName = "Testing"

    SetComputerName(computerName.ToString)
是这样吗?因为它不会更改计算机名


非常感谢您的帮助。

我以前通过让我的vb.net代码生成一个bat文件,然后执行它来实现这一点。bat脚本包含用于重命名PC的wmic命令

wmic computersystem where name="%computername%" call rename name="[NEW PC NAME]"
您可以动态地将新名称编译到bat文件中。vb.net代码只需要通过一个参数获取新名称,或者如果您使用的是windows窗体,则需要一个文本框

VB部分:

Public rename As String = "wmic computersystem where name=""%computername%"" call rename name="
...
dim source as new system.text.stringbuilder
source.AppendLine("@echo off")
source.AppendLine(rename + """" + [put your new hostname here] + """")
source.AppendLine("shutdown /r -t 10") 'PC rename only works after reboot. omit this line to reboot later
source.AppendLine("del %0") 'this will make the bat file delete itself after it runs
IO.File.WriteAllText("source.bat", source.ToString())
process.start("source.bat")

请记住,除了wmi中已经内置的内容外,这绝对没有错误检查。如果要执行诸如检查空白、禁止字符或确保新主机名字符串少于15个字符(这是Windows设置的最大值)之类的操作,则需要更多的代码。这也只有在vb.net代码以管理员权限执行时才起作用。您可能还会看到Windows CMD短暂打开。

您是否使用管理员权限运行应用程序?另外,您应该检查函数的结果,如果失败,请使用GetLastError检查错误。您重新启动了计算机吗?SetComputerName为本地计算机设置新的NetBIOS名称。名称存储在注册表中,名称更改将在用户下次重新启动计算机时生效。在您的真实代码中,是否检查了返回值?返回值为1。在我做了更改后,我重新启动了电脑,但什么也没有