2015-04-14 52 views
4

我需要從C#應用程序添加DNS後綴:WMI Win32_NetworkAdapterConfiguration並SetDNSSuffixSearchOrder方法

基於這方面的工作VB腳本:

On Error Resume Next 

strComputer = "." 
arrNewDNSSuffixSearchOrder = Array("my.first.suffix", "my.second.suffix") 

Set objWMIService = GetObject("winmgmts:{impersonationLevel=impersonate}!\\" & strComputer & "\root\cimv2") 
Set colNicConfigs = objWMIService.ExecQuery("SELECT * FROM Win32_NetworkAdapterConfiguration WHERE IPEnabled = True") 

For Each objNicConfig In colNicConfigs 
    strDNSHostName = objNicConfig.DNSHostName 
Next 
WScript.Echo VbCrLf & "DNS Host Name: " & strDNSHostName 

For Each objNicConfig In colNicConfigs 
    WScript.Echo VbCrLf & " Network Adapter " & objNicConfig.Index & VbCrLf & objNicConfig.Description & VbCrLf & " DNS Domain Suffix Search Order - Before:" 
    If Not IsNull(objNicConfig.DNSDomainSuffixSearchOrder) Then 
    For Each strDNSSuffix In objNicConfig.DNSDomainSuffixSearchOrder 
     WScript.Echo "  " & strDNSSuffix 
    Next 
    End If 
Next 

WScript.Echo VbCrLf & String(80, "-") 

Set objNetworkSettings = objWMIService.Get("Win32_NetworkAdapterConfiguration") 
intSetSuffixes = objNetworkSettings.SetDNSSuffixSearchOrder(arrNewDNSSuffixSearchOrder) 
If intSetSuffixes = 0 Then 
    WScript.Echo VbCrLf & "Replaced DNS domain suffix search order list." 
ElseIf intSetSuffixes = 1 Then 
    WScript.Echo VbCrLf & "Replaced DNS domain suffix search order list." & _ 
    VbCrLf & " Must reboot." 
Else 
    WScript.Echo VbCrLf & "Unable to replace DNS domain suffix " & _ 
    "search order list." 
End If 

WScript.Echo VbCrLf & String(80, "-") 

Set colNicConfigs = objWMIService.ExecQuery _ 
("SELECT * FROM Win32_NetworkAdapterConfiguration WHERE IPEnabled = True") 
For Each objNicConfig In colNicConfigs 
    WScript.Echo VbCrLf & " Network Adapter " & objNicConfig.Index & VbCrLf & objNicConfig.Description & VbCrLf & " DNS Domain Suffix Search Order - After:" 
    If Not IsNull(objNicConfig.DNSDomainSuffixSearchOrder) Then 
    For Each strDNSSuffix In objNicConfig.DNSDomainSuffixSearchOrder 
     WScript.Echo "  " & strDNSSuffix 
    Next 
    End If 
Next 

我結束了本次非運行的C#代碼:

using System; 
using System.Diagnostics; 
using System.Management; 

namespace ChangeDnsSuffix 
{ 
    class Program 
    { 
     static void Main(string[] args) 
     { 
      string[] aSuffix = { "my.first.suffix", "my.second.suffix" }; 
      Int32 ret = SetDNSSuffixSearchOrder(aSuffix); 
     } 

     private static Int32 SetDNSSuffixSearchOrder(string[] DNSDomainSuffixSearchOrder) 
     { 
      try 
      { 
       ManagementPath mp = new ManagementPath((@"\\.\root\cimv2:Win32_NetworkAdapterConfiguration")); 

       InvokeMethodOptions Options = new InvokeMethodOptions(); 
       Options.Timeout = new TimeSpan(0, 0, 10); 
       ManagementClass WMIClass = new ManagementClass("Win32_NetworkAdapterConfiguration"); 
       ManagementBaseObject InParams = WMIClass.GetMethodParameters("SetDNSSuffixSearchOrder"); 
       InParams["DNSDomainSuffixSearchOrder"] = DNSDomainSuffixSearchOrder; 

       ManagementBaseObject OutParams = null; 
       OutParams = InvokeMethod(mp.Path,"SetDNSSuffixSearchOrder", InParams, Options); 

       Int32 numericResult = Convert.ToInt32(OutParams["ReturnValue"]); 
       return numericResult; 

      } 
      catch (Exception exception) 
      { 
       Debug.WriteLine(exception.Message); 
       return 0; 
      } 
     } 

     public static ManagementBaseObject InvokeMethod(string ObjectPath, string MethodName, ManagementBaseObject InParams, InvokeMethodOptions Options) 
     { 
      ManagementObject WMIObject = new ManagementObject(ObjectPath); 
      ManagementBaseObject OutParams = WMIObject.InvokeMethod(MethodName, InParams, Options); 

      if (InParams != null) 
      { 
       InParams.Dispose(); 
      } 

      return OutParams; 
     } 
    } 
} 

我試了很多代碼。一旦錯誤是「無效方法」,一旦代碼殺死了我的VS實例,目前的錯誤是:

由於對象的當前狀態,操作無效。

我沒有運行編譯的應用程序和Visual Studio提升和不升級,沒有區別。

幫助真的很感激!

基督教


基於什麼manuchao貢獻,我現在有:

using System; 
using System.Diagnostics; 
using System.Management; 
using System.Management.Instrumentation; 
using System.Collections.Generic; 

namespace ChangeDnsSuffix 
{ 
    class Program 
    { 
     static void Main(string[] args) 
     { 
      foreach (ManagementObject mo in GetSystemInformation()) 
      { 
       mo.SetPropertyValue("DNSDomainSuffixSearchOrder", new object[] { "suffix.com" }); 
       mo.Put(); 
      } 
     } 

     private static IEnumerable<ManagementObject> GetSystemInformation() 
     { 
      ManagementObjectCollection collection = null; 
      ManagementScope Scope = new ManagementScope(String.Format("\\\\{0}\\root\\cimv2", ".")); 

      try 
      { 
       SelectQuery query = new SelectQuery("select * from Win32_NetworkAdapterConfiguration"); 
       Scope.Connect(); 
       ManagementObjectSearcher searcher = new ManagementObjectSearcher(Scope, query); 
       collection = searcher.Get(); 
      } 
      catch (ManagementException ex) 
      { 
       Console.WriteLine(ex.Message); 
      } 
      catch (UnauthorizedAccessException ex) 
      { 
       throw new ArgumentException(ex.Message); 
      } 

      if (collection == null) { yield break; } 

      foreach (ManagementObject obj in collection) 
      { 
       yield return obj; 
      } 
     } 

     public IEnumerable<PropertyData> GetPropertiesOfManagmentObj(ManagementObject obj) 
     { 
      var properties = obj.Properties; 
      foreach (PropertyData item in properties) 
      { 
       yield return item; 
      } 
      yield break; 
     } 
    } 
} 

結果:

'提供程序無法進行嘗試的操作'

+0

所以你把一個賞金對這一問題才能得到別人寫的這部分代碼給你? – Claies

回答

1

我做了一些調整,而下面的方法成功地將我的機器上的DNS搜索後綴:

public static Int32 SetDNSSuffixSearchOrder(string[] DNSDomainSuffixSearchOrder) 
{ 
    try 
    { 
     var options = new InvokeMethodOptions(); 
     options.Timeout = new TimeSpan(0, 0, 10); 

     var wmiClass = new ManagementClass("Win32_NetworkAdapterConfiguration"); 
     var inParams = wmiClass.GetMethodParameters("SetDNSSuffixSearchOrder"); 

     inParams["DNSDomainSuffixSearchOrder"] = DNSDomainSuffixSearchOrder; 

     var outParams = wmiClass.InvokeMethod("SetDNSSuffixSearchOrder", inParams, options); 

     var numericResult = Convert.ToInt32(outParams["ReturnValue"]); 
     return numericResult; 

    } 
    catch (Exception exception) 
    { 
     Debug.WriteLine(exception.Message); 
     return 0; 
    } 
} 
0

DNSDomainSuffixSearchOrder是屬性而不是方法。 如果你想設置它,你必須調用是這樣的:

netWorkDevice["DNSDomainSuffixSearchOrder"] = new object[] {"doamin.int", "blubb.see"}; 

printer.Put(); //save 

樓下是讀取屬性代碼。

我的WMIHelper類中的方法。您需要導入:

using System.Management; 
using System.Management.Instrumentation; 

讓它工作。如果你是在本地計算機上使用此代碼,你必須註釋掉其開頭部分「//開始:」以「//結束:」

public IEnumerable<ManagementObject> GetSystemInformation() 
{ 
     ManagementScope scope = new ManagementScope(String.Format("\\\\{0}\\root\\cimv2", "hostname")); 
     ManagementObjectCollection collection = null; 

     //BEGIN: This part you will need if you want to acces other computers in your network you might wanna comment this part. 
     string computerName = "Hostname"; 
     string userName = "username"; 
     string password = "ThePW"; 

     try 
     { 

      var options = new ConnectionOptions 
      { 
       Authentication = AuthenticationLevel.Packet, 
       EnablePrivileges = true, 
       Impersonation = ImpersonationLevel.Impersonate, 
       Username = this.UserName, 
       SecurePassword = this.Password, 
       Authority = "ntlmdomain:" + Environment.UserDomainName 
      }; 
      scope.Options = options; 
      //END: Part which you need to connect to remote pc 

      SelectQuery query = new SelectQuery("select * from Win32_NetworkAdapterConfiguration"); 

      Scope.Connect(); 

      ManagementObjectSearcher searcher = new ManagementObjectSearcher(scope, query); 
      collection = searcher.Get(); 
     } 
     catch (ManagementException ex) 
     { 
      Console.WriteLine(ex.Message); 
     } 
     catch (UnauthorizedAccessException ex) 
     { 
      throw new ArgumentException(ex.Message); 
     } 

     if (collection == null) { yield break; } 

     foreach (ManagementObject obj in collection) 
     { 
      yield return obj; 
     } 
} 

public IEnumerable<PropertyData> GetPropertiesOfManagmentObj(ManagementObject obj) 
{ 
     var properties = obj.Properties; 
     foreach (PropertyData item in properties) 
     { 
      yield return item; 
     } 

     yield break; 
} 

測試類

private void HelperMethod() 
{ 
     netWorkDevice["DNSDomainSuffixSearchOrder"] = new object[] {"doamin.int", "blubb.see"}; 

    foreach(ManagementObject netWorkDevice in help.GetSystemInformation()) 
    { 
      netWorkDevice["DNSDomainSuffixSearchOrder"] = new object[] {"doamin.int", "blubb.see"}; 
      printer.Put(); //Save 

      Console.WriteLine(); 
      Console.WriteLine(); 
      Console.WriteLine("Next Device"); 
      Console.WriteLine(); 

      foreach(var prop in help.GetPropertiesOfManagmentObj(netWorkDevice)) 
      { 
       if (prop.Name != "DNSDomainSuffixSearchOrder") { continue; } 
       if (prop.Value == null) { continue; } 

       foreach(var value in (string[])prop.Value) 
       { 
        Console.WriteLine(prop.Name + "   " + value); 
       } 
      } 
    } 
} 
+0

1,感謝您的回覆。 2nd,DNSDomainSuffixSearchOrder當然是一個屬性,但SetDNSSuffixSearchOrder是一個方法。我無法看到我調用屬性而不是方法的點/部分。 3,我可以讀取DNS後綴,沒問題,但我需要設置它。我看不到你的代碼中你設置或附加dns後綴的部分,所以對我來說毫無價值,對不起! –

+0

我更新了代碼。通過ManagementObject的Put()方法,您可以更新您的值。 – C0d1ngJammer

+0

感謝代碼編輯。 範圍聲明丟失。我認爲它是一個ManagementScope?請幫助/建議。 –

相關問題