我正在 VB.Net 中编写一个 Windows 窗体应用程序,它将(除其他外)更改 IP 地址、默认网关、子网掩码,并将 IP 地址设置为仅在 Windows 7 的图像上的静态。未使用 Sysprep。我搜索了谷歌,只找到了 2 个选项。我不相信第一个解决方案对我有用,因为我不一定知道连接的名称。它使用 netsh 更改 IP 设置。我打算给出这个例子的链接,但我不能发布超过 2 个链接......
第二个解决方案显示在此链接(VB.Net 版本),原始代码在这里(C# 版本)。这个解决方案使用了我真的不太了解的 WMI。
当我调试代码并查看代码似乎正确执行的所有内容时,IP 地址仍设置为 DHCP,所有其他设置仍然相同。所以,基本上,什么给了?为什么这段代码似乎不起作用?
这是我的代码。我只做了一些改动:
'Changed the 3 IPs below
Dim IPAddress As String = "192.168.1.105"
Dim SubnetMask As String = "255.255.252.0"
Dim Gateway As String = "192.168.1.100"
Dim objMC As ManagementClass = New ManagementClass("Win32_NetworkAdapterConfiguration")
Dim objMOC As ManagementObjectCollection = objMC.GetInstances()
For Each objMO As ManagementObject In objMOC
If (Not CBool(objMO("IPEnabled"))) Then
Continue For
End If
Try
Dim objNewIP As ManagementBaseObject = Nothing
Dim objSetIP As ManagementBaseObject = Nothing
Dim objNewGate As ManagementBaseObject = Nothing
objNewIP = objMO.GetMethodParameters("EnableStatic")
objNewGate = objMO.GetMethodParameters("SetGateways")
'Set DefaultGateway
objNewGate("DefaultIPGateway") = New String() {Gateway}
objNewGate("GatewayCostMetric") = New Integer() {1}
'Set IPAddress and Subnet Mask
objNewIP("IPAddress") = New String() {IPAddress}
objNewIP("SubnetMask") = New String() {SubnetMask}
objSetIP = objMO.InvokeMethod("EnableStatic", objNewIP, Nothing)
objSetIP = objMO.InvokeMethod("SetGateways", objNewGate, Nothing)
'Changed this line so I could see if it was executing all of the way
MessageBox.Show("Updated IPAddress, SubnetMask and Default Gateway!")
Catch ex As Exception
MessageBox.Show("Unable to Set IP : " & ex.Message)
End Try
Next objMO