1
我正在VB.Net中编写一个Windows Forms应用程序,它将(除其他外)更改IP地址,默认网关,子网掩码并将IP地址设置为静态只有Winfows 7。 Sysprep没有被使用。我搜索了Google,只有2个选项。我不相信第一种解决方案会适用于我,因为我不一定知道连接的名称。它使用netsh来更改IP设置。我打算给这个例子的链接,但我不能发布超过2个链接...在VB.Net中更改IP地址
第二个解决方案显示在this link (the VB.Net version)和原始代码是here (the C# version)。这个解决方案使用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
[这是链接(http://www.codeproject.com/Questions/443895/ip-address-changer-using-vb-net),我无法在上面的柱提供。 – Thomas927 2013-02-08 16:54:17
我可以在7个小时内回答我自己的问题。 – Thomas927 2013-02-08 17:31:48
*不*忽视的InvokeMethod()的返回值,它会提供一个错误代码,如果该方法失败。 – 2013-02-08 17:32:57