利用WMI修改计算机网络设置

来源:互联网 发布:c51单片机信号发生器 编辑:程序博客网 时间:2024/06/06 16:29
  • 获取本机网卡

 

 /// <summary>
        
/// 获取网卡列表
        
/// </summary>

        public ArrayList GetAllNetCards()
        
{
            ArrayList myary 
= new ArrayList();
            ManagementObjectSearcher searcher 
= new ManagementObjectSearcher("SELECT * FROM Win32_NetworkAdapterConfiguration");

            
foreach (ManagementObject share in searcher.Get())
            
{
                
if ((share["IPAddress"!= null))
                
{
                    myary.Add(share[
"Description"].ToString());
                }

            }

            
return myary;
        }

 

  • 得到网卡信息

 

   /// <summary>
        
/// 得到网卡信息
        
/// </summary>
        
/// <param name="description"></param>

        public NetWorkSetingStruct GetNetCardConfiguraton(string description)
        
{
            NetWorkSetingStruct NWSS 
= new NetWorkSetingStruct();

            
if (description == null | description.Length == 0)
            
{
                
return NWSS;
            }

            
else
            
{
                ManagementObjectSearcher searcher 
= new ManagementObjectSearcher("SELECT * FROM Win32_NetworkAdapterConfiguration WHERE Description="" + description + """);
                
foreach (ManagementObject share in searcher.Get())
                
{
                    NWSS.IP 
= ((string[])share["IPAddress"])[0];
                    NWSS.SubNet 
= ((string[])share["IPSubnet"])[0];
                    NWSS.DefaultGateWay 
= ((string[])share["DefaultIPGateway"])[0];
                    NWSS.DHCPEnable 
= (bool)share["DHCPEnabled"];
                    
int i;

                    
for (i = 0; i <= ((string[])share["DNSServerSearchOrder"]).GetLength(0- 1; i++)
                    
{
                        
//txt_DNS.Text += ((string[])share["DNSServerSearchOrder"])[i] + "-";
                        NWSS.DNS = ((string[])share["DNSServerSearchOrder"])[i];
                    }

                    
if (i >= 2)
                    
{
                        
//this.txt_DNS.Foreground =  "#FFFFFFFF";
                    }

                    
else
                    
{

                    }

                    
//this.txt_DNS.Text = this.txt_DNS.Text.Remove(this.txt_DNS.Text.Length - 1, 1);
                    
//this.textBox5.Text = share["MACAddress"].ToString();
                    break;
                }

            }

            
return NWSS;
        }

 

  • 得到所有有打印机

 



        
/// <summary>
        
/// 得到所有有打印机
        
/// </summary>
        
/// <returns></returns>

        public ArrayList GetAllPrinter()
        
{
            ArrayList myary 
= new ArrayList();
            
try
            
{
                ManagementObjectSearcher searcher 
= new ManagementObjectSearcher("SELECT * FROM Win32_Printer");
                
foreach (ManagementObject share in searcher.Get())
                
{
                    
string name = share["Name"].ToString();
                    myary.Add(name);
                }

                
return myary;
            }

            
catch
            
{
                
throw new ApplicationException("检测到打印机服务[Print Spooler]未启动!");
            }

            
//grv_Printer.DataSource = dt;
        }

 

  • 防火墙关闭开启
    //需要引用 using NetFwTypeLib;VISTA下开启防火墙需要有管理员权限,但关闭防火墙还暂时无法实现
     /// <summary>
            
    /// XP防火墙关闭开启
            
    /// </summary>
            
    /// <param name="enable"></param>

            public bool SetFireWall_XP(bool enable)
            
    {
                INetFwMgr NetFwMgr;
                INetFwProfile NetFwProfile;
                
    //INetFwPolicy NetFwPolicy2;
                try
                
    {
                    Type NetFwMgrType 
    = Type.GetTypeFromProgID("HNetCfg.FwMgr");
                    
    object NetFwMgrObject = Activator.CreateInstance(NetFwMgrType);
                    NetFwMgr 
    = (INetFwMgr)NetFwMgrObject;
                    NetFwProfile 
    = NetFwMgr.LocalPolicy.CurrentProfile;

                    NetFwProfile.FirewallEnabled 
    = enable;
                    
    return true;

                }

                
    catch (Exception e)
                
    {
                    
    throw new ApplicationException("无法设置防火墙." + e.Message);
                    
    return false;
                }

            }

 

  • 得到IE代理

 

/// <summary>
        
/// 得到所有代理
        
/// </summary>
        
/// <returns></returns>

        public ProxyStruct GetAllProxy()
        
{
            ProxyStruct PS 
= new ProxyStruct();
            
try
            
{
                ManagementObjectSearcher searcher 
= new ManagementObjectSearcher("SELECT * FROM Win32_Proxy");
                
foreach (ManagementObject share in searcher.Get())
                
{
                    PS.ProxyIP 
= share["ProxyServer"].ToString();
                    PS.ProxyPort 
= share["ProxyPortNumber"].ToString();
                }

            }

            
catch (Exception ex)
            
{
                
throw new ApplicationException("无法获取代理信息." + ex.Message);
            }

            
return PS;
        }

 

  • 获取主页
    /// <summary>
            
    /// 得到主页
            
    /// </summary>
            
    /// <returns></returns>

            public string GetHomePage()
            
    {
                
    string startPageURL;
                RegistryKey hklm 
    = Registry.CurrentUser;
                RegistryKey software 
    = hklm.OpenSubKey("Software"false);
                RegistryKey Microsoft 
    = software.OpenSubKey("Microsoft"false);
                RegistryKey InternetExplorer 
    = Microsoft.OpenSubKey("Internet Explorer"false);
                RegistryKey Main 
    = InternetExplorer.OpenSubKey("Main");
                startPageURL 
    = Main.GetValue("Start Page").ToString();
                
    return startPageURL;
            }

 

  • 设置主页

 

 /// <summary>
        
/// 设置主页
        
/// </summary>
        
/// <param name="startPageURL"></param>

        public void SetHomePage(string startPageURL)
        
{
            
if (startPageURL != "")
            
{
                RegistryKey hklm 
= Registry.LocalMachine;
                RegistryKey software 
= hklm.OpenSubKey("Software"false);
                RegistryKey Microsoft 
= software.OpenSubKey("Microsoft"false);
                RegistryKey InternetExplorer 
= Microsoft.OpenSubKey("Internet Explorer"false);
                RegistryKey Main 
= InternetExplorer.OpenSubKey("Main"true);
                Main.SetValue(
"Start Page", startPageURL);
                hklm.Close();
                software.Close();
                Microsoft.Close();
                InternetExplorer.Close();
                Main.Close();

                RegistryKey hkcu 
= Registry.CurrentUser;
                RegistryKey software2 
= hkcu.OpenSubKey("Software"false);
                RegistryKey Microsoft2 
= software2.OpenSubKey("Microsoft"false);
                RegistryKey InternetExplorer2 
= Microsoft2.OpenSubKey("Internet Explorer"false);
                RegistryKey Main2 
= InternetExplorer2.OpenSubKey("Main"true);
                Main2.SetValue(
"Start Page", startPageURL);
                hkcu.Close();
                software2.Close();
                Microsoft2.Close();
                InternetExplorer2.Close();
                Main2.Close();
            }

        }

 

  • 设置IE代理

 

 public void SetProxy_XP(ProxyStruct PS)
        
{
            ManagementObjectSearcher searcher 
= new ManagementObjectSearcher("SELECT * FROM Win32_Proxy");

            
foreach (ManagementObject share in searcher.Get())
            
{
                
object[] obj = { PS.ProxyIP, PS.ProxyPort };
                share.InvokeMethod(
"SetProxySetting", obj);
                
//MessageBox.Show(" 设置成功!");
                
//MessageBox.Show(share.GetText(TextFormat.Mof));
            }

        }


        
public void SetNoProxy()
        
{
            ManagementObjectSearcher searcher 
= new ManagementObjectSearcher("SELECT * FROM Win32_Proxy");

            
foreach (ManagementObject share in searcher.Get())
            
{

                share.InvokeMethod(
"SetProxySetting"null);
                
//MessageBox.Show(" 设置成功!");
                
//MessageBox.Show(share.GetText(TextFormat.Mof));
            }

        }

 

  • 手动设置网卡

 

 /// <summary>
        
/// 手动设置网卡
        
/// </summary>
        
/// <param name="netCardName">网卡名称</param>
        
/// <param name="ip">IP地址</param>
        
/// <param name="subnet">子网掩码</param>
        
/// <param name="gateway">网关</param>
        
/// <param name="DNS">DNS</param>

        public bool SetNetWork(string netCardName, string ip, string subnet, string gateway, string DNS)
        
{
            ManagementObjectSearcher searcher 
= new ManagementObjectSearcher("SELECT * FROM Win32_NetworkAdapterConfiguration WHERE Description="" + netCardName + """);
            
long iResult = 0;
            
// 判断是否修改成功。如果成功,后面的三个方法返回值都是0,注意返回的值是 Uint32 类型。 
            foreach (ManagementObject share in searcher.Get())
            
{
                
//Console.WriteLine(share.GetText(TextFormat.Mof));
                if ((share["IPAddress"!= null))
                
{
                    
//set address 
                    string[] ipAddresses = { ip };
                    
// IP 地址 
                    string[] ipSubnetmask = { subnet };
                    
//掩码 
                    object[] objpara = { ipAddresses, ipSubnetmask };
                    
object res = share.InvokeMethod("EnableStatic", objpara);
                    iResult 
+= Convert.ToInt64(res);
                    
string[] ipGateWay = { gateway };
                    
//网关 
                    UInt16[] GatewayCostMetric = { UInt16.Parse("1") };
                    
object[] objpara1 = { ipGateWay, GatewayCostMetric };
                    iResult 
+= Convert.ToInt64(share.InvokeMethod("SetGateways", objpara1));

                    
//set Dns Server Serach Order 

                    
// 多个dns 中间以减号分开 

                    
//if (DNS.IndexOf("-") > 0)
                    
//{
                    
//    string[] dnsServers = DNS.Split('-');
                    
//    object[] objpara2 = { dnsServers };
                    
//    iResult += Convert.ToInt32(share.InvokeMethod("SetDNSServerSearchOrder", objpara2));
                    
//}
                    
//else
                    
//{
                    string[] dnsServers = { DNS };
                    
object[] objpara2 = { dnsServers };
                    iResult 
+= Convert.ToInt64(share.InvokeMethod("SetDNSServerSearchOrder", objpara2));
                    
//}

                }

            }


            
if (iResult == 0)
            
{
                
return true;
            }

            
else
            
{
                
return false;
                
// MessageBox.Show("IP修改失败,检查输入的格式和您是否有权限");
            }

        }

 

  • 设置默认打印机

 

/// <summary>
        
/// 设置默认打印机
        
/// </summary>
        
/// <param name="printerName"></param>

        public void SetDefaultPrinter(string printerName)
        
{
            
try
            
{
                ManagementObjectSearcher searcher 
= new ManagementObjectSearcher("SELECT * FROM Win32_Printer");
                
foreach (ManagementObject share in searcher.Get())
                
{
                    
if (share["Name"].ToString() == printerName)
                    
{
                        share.InvokeMethod(
"SetDefaultPrinter"null);
                    }

                    
//MessageBox.Show(share.GetText(TextFormat.Mof));
                }

            }

            
catch
            
{
                
throw new ApplicationException("无法设置为默认打印机.");
            }

        }

 

  • 获取默认打印机

 


        
/// <summary>
        
/// 获取默认打印机
        
/// </summary>
        
/// <returns></returns>

        public string GetDefaultPrinter()
        
{
            
string printerName = "";
            ManagementObjectSearcher searcher 
= new ManagementObjectSearcher("SELECT * FROM Win32_Printer");
            
foreach (ManagementObject share in searcher.Get())
            
{
                
if (share["Default"].ToString() == "True")
                
{
                    printerName 
= share["Name"].ToString();

                }

                
//MessageBox.Show(share.GetText(TextFormat.Mof));
            }

            
return printerName;
        }

 

  • 动态获取DHCP

 

 /// <summary>
        
/// 动态取DHCPEnabled
        
/// </summary>

        public void SetDHCPEnable(bool isXP)
        
{
            ManagementBaseObject iObj 
= null;
            ManagementBaseObject oObj 
= null;
            ManagementClass mc 
= new ManagementClass("Win32_NetworkAdapterConfiguration");
            ManagementObjectCollection moc;
            moc 
= mc.GetInstances();
            
foreach (ManagementObject mo in moc)
            
{
                
if (!(bool)mo["IPEnabled"]) continue;
                
if (!(bool)mo["DHCPEnabled"])
                
{
                    
if (isXP)
                    
{
                        
//修改DNS改为自动获取
                        RegistryKey hklm = Registry.LocalMachine;
                        RegistryKey SYSTEM 
= hklm.OpenSubKey("SYSTEM"false);
                        RegistryKey CurrentControlSet 
= SYSTEM.OpenSubKey("CurrentControlSet"false);
                        RegistryKey Services 
= CurrentControlSet.OpenSubKey("Services"false);
                        RegistryKey Tcpip 
= Services.OpenSubKey("Tcpip"true);
                        RegistryKey Parameters 
= Tcpip.OpenSubKey("Parameters"true);
                        RegistryKey Adapters 
= Parameters.OpenSubKey("Adapters"true);
                        RegistryKey Interfaces 
= Parameters.OpenSubKey("Interfaces");
                        
string[] subkeys = Adapters.GetSubKeyNames();
                        
foreach (string str in subkeys)
                        
{
                            
if (str.StartsWith("{"))
                            
{
                                RegistryKey curradpt 
= Interfaces.OpenSubKey(str, true);
                                
string val = curradpt.GetValue("NameServer").ToString();
                                curradpt.SetValue(
"NameServer""");
                            }

                        }

                    }

                    iObj 
= mo.GetMethodParameters("EnableDHCP");
                    oObj 
= mo.InvokeMethod("EnableDHCP", iObj, null);

                    
//iObj = mo.GetMethodParameters("SetDynamicDNSRegistration");
                    
//oObj = mo.InvokeMethod("SetDynamicDNSRegistration", iObj, null);
                    
//iObj = mo.GetMethodParameters("RenewDHCPLeaseAll");
                    
//oObj = mo.InvokeMethod("RenewDHCPLeaseAll", iObj, null);
                }

                
else
                
{
                    
//iObj = mo.GetMethodParameters("ReleaseDHCPLeaseAll");
                    
//oObj = mo.InvokeMethod("ReleaseDHCPLeaseAll", iObj, null);
                    
//iObj = mo.GetMethodParameters("RenewDHCPLeaseAll");
                    
//oObj = mo.InvokeMethod("RenewDHCPLeaseAll", iObj, null);

                    
//iObj = mo.GetMethodParameters("RenewDHCPLease");
                    
//oObj = mo.InvokeMethod("RenewDHCPLease", iObj, null);
                }

            }

        }

 

 

代码太乱了,呵呵~VISTA下动态获取IP时会有问题,是微软的一个BUG,现在还没有发布补丁,可以设置成功,但在网卡IPV4中看却显示不正常(子网掩码与网关不正确),但在IPCONFIG中显示正常并可以成功访问网络.

在VISTA下防火墙无法关闭,注册表与INetFwMgr都无法关闭,不知道各位有什么好的办法.其它打印机与主页都可以正常修改.

IE代理服务器的WMI类在VISTA下已经删除,在MSDN上未找到其替代的类,暂时无法修改.

原创粉丝点击