2013-02-08 142 views
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 
+0

[這是鏈接(http://www.codeproject.com/Questions/443895/ip-address-changer-using-vb-net),我無法在上面的柱提供。 – Thomas927 2013-02-08 16:54:17

+0

我可以在7個小時內回答我自己的問題。 – Thomas927 2013-02-08 17:31:48

+0

*不*忽視的InvokeMethod()的返回值,它會提供一個錯誤代碼,如果該方法失敗。 – 2013-02-08 17:32:57

回答

0

我可以回答我的問題。我在洗澡的時候想到了這個問題(怎麼說得很對?)。因爲這是Windows 7中,所有我需要是右鍵單擊並運行該程序作爲管理員。