Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/278.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# WMI Win32_网络适配器配置和SetDNSSuffixSearchOrder方法_C#_Wmi - Fatal编程技术网

C# WMI Win32_网络适配器配置和SetDNSSuffixSearchOrder方法

C# WMI Win32_网络适配器配置和SetDNSSuffixSearchOrder方法,c#,wmi,C#,Wmi,我需要从C应用程序中附加DNS后缀: 基于此工作的VB脚本: On Error Resume Next strComputer = "." arrNewDNSSuffixSearchOrder = Array("my.first.suffix", "my.second.suffix") Set objWMIService = GetObject("winmgmts:{impersonationLevel=impersonate}!\\" & strComputer & "\r

我需要从C应用程序中附加DNS后缀:

基于此工作的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;
        }
    }
}
结果:

“提供程序无法执行尝试的操作”

DNSDomainSuffixSearchOrder是一个属性而不是一个方法。 如果要设置它,必须调用如下内容:

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

printer.Put(); //save
下面是读取属性的代码

我的WMIHelper类中的方法。您需要导入:

using System.Management;
using System.Management.Instrumentation;
让它工作。如果在本地计算机上使用此代码,则必须注释掉以//Begin:到//End:开头的部分

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;
 }

我做了一些调整,以下方法成功地在我的机器上设置了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;
    }
}

谢谢你的回复。第二,DNSDomainSuffixSearchOrder当然是一个属性,但SetDNSSuffixSearchOrder是一个方法。我看不到调用属性而不是方法的点/部分。第三,我可以读取DNS后缀,没有问题,但我需要设置它。我看不到您的代码中设置或附加dns后缀的部分,因此对我来说毫无价值,抱歉!我更新了代码。使用ManagementObject的Put方法,您可以更新您的值。感谢您的代码编辑。缺少范围声明。我想这是一个管理范围?请提供帮助/建议。刚刚添加了范围。应该没问题。请参阅初始问题中的示例代码-printer.put应该是netWorkDevice.put,对吗?它仍然没有做它应该做的。所以你在这个问题上悬赏是为了让别人为你写这段代码?
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;
    }
}