none
c# 用ManageWifi包搜索WIFI连接WIFI RRS feed

  • 问题

  • 各位大佬,我最近再开发一个项目,项目需求,需要我用PC连接指定WIFI。我在网上搜索到了MangedWifi这个包,可以很方便的搜索和连接WIFI。所以,我决定直接使用这个包,来实现我的需求。 

    下面是我的代码 

    using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using NativeWifi; using System.IO; namespace ConsoleApp_WIFI { class MyWifi { public List<WIFISSID> ssids = new List<WIFISSID>(); //用于存储所扫描到的SSID public string ssidWantCon = ""; public MyWifi() { ssids.Clear(); } static string GetStringForSSID(Wlan.Dot11Ssid ssid) { return Encoding.UTF8.GetString(ssid.SSID, 0, (int)ssid.SSIDLength); } /// <summary> /// 枚举所有无线设备接收到的SSID /// </summary> public void ScanSSID() { ssids.Clear(); //清除以前扫描的SSID WlanClient client = new WlanClient(); foreach (WlanClient.WlanInterface wlanIface in client.Interfaces) { // Lists all networks with WEP security Wlan.WlanAvailableNetwork[] networks = wlanIface.GetAvailableNetworkList(0); foreach (Wlan.WlanAvailableNetwork network in networks) //存储SSID的信息 { WIFISSID targetSSID = new WIFISSID(); targetSSID.wlanInterface = wlanIface; //无线网卡名称 targetSSID.wlanSignalQuality = (int)network.wlanSignalQuality; //信号指令 targetSSID.SSID = GetStringForSSID(network.dot11Ssid); //AP名称 //targetSSID.SSID = Encoding.Default.GetString(network.dot11Ssid.SSID, 0, (int)network.dot11Ssid.SSIDLength); targetSSID.dot11DefaultAuthAlgorithm = network.dot11DefaultAuthAlgorithm.ToString(); //默认接入网络验证算法 targetSSID.dot11DefaultCipherAlgorithm = network.dot11DefaultCipherAlgorithm.ToString(); ssids.Add(targetSSID); //扫描到的SSID 加入到LIST中 } } } // EnumSSID /// <summary> /// 连接到加密的SSID /// </summary> /// <param name="ssid"></param> public void ConnectToSSID(WIFISSID ssid, string key) { // Connects to a known network with WEP security string profileName = ssid.SSID; // this is also the SSID string mac = StringToHex(profileName); // string auth = "WPA2PSK"; string cipher = "AES"; string keytype = "passPhrase"; //从文件中读取XML字符串 StreamReader sr = new StreamReader("C:\\Users\\dgl\\Documents\\Code-Project\\c#proj\\military-proj\\ConsoleApp_WIFI\\ConsoleApp_WIFI\\bin\\Debug\\wifi.xml", System.Text.Encoding.UTF8); string readContent = sr.ReadToEnd().Replace("\r\n", ""); Console.WriteLine("readContent:{0}", readContent); string xml_str = readContent; Console.WriteLine("xml_str:{0}", xml_str); ssid.wlanInterface.SetProfile(Wlan.WlanProfileFlags.AllUser, xml_str, true); //配置WIFI的Profile bool success = ssid.wlanInterface.ConnectSynchronously(Wlan.WlanConnectionMode.Profile, Wlan.Dot11BssType.Any, profileName, 15000);//连接WIFI if (!success) { Console.WriteLine("连接网络失败"); } }

     public bool find_Ssid_from_ssidList(WIFISSID arg) //从LIST中查找指定SSID
            {


                if (arg.SSID == ssidWantCon)
                {
                    return true;
                }
                return false;

            }



            /// <summary>  
            /// 字符串转Hex  
            /// </summary>  
            /// <param name="str"></param>  
            /// <returns></returns>  
            public static string StringToHex(string str)
            {
                StringBuilder sb = new StringBuilder();
                byte[] byStr = System.Text.Encoding.Default.GetBytes(str); //默认是System.Text.Encoding.Default.GetBytes(str)  
                for (int i = 0; i < byStr.Length; i++)
                {
                    sb.Append(Convert.ToString(byStr[i], 16));
                }

                return (sb.ToString().ToUpper());
            }
    //WLAN事件变化时的通知函数
            public static void WlanIface_WlanConnectionNotification(Wlan.WlanNotificationData notifyData, Wlan.WlanConnectionNotificationData connNotifyData)
            {
                Console.WriteLine(".....................");
                Console.WriteLine(notifyData.NotificationCode);
                Console.WriteLine(notifyData.notificationSource);
            }

        }


        class WIFISSID
        {
            public string SSID = "NONE";
            public string dot11DefaultAuthAlgorithm = "";
            public string dot11DefaultCipherAlgorithm = "";
            public bool networkConnectable = true;
            public string wlanNotConnectableReason = "";
            public int wlanSignalQuality = 0;
            public WlanClient.WlanInterface wlanInterface = null;
        }

    }  
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Threading.Tasks;
    using System.Threading;
    
    
    
    namespace ConsoleApp_WIFI
    {
        class Program
        {
            static void Main(string[] args)
            {
    
                MyWifi mw = new MyWifi();
    
                mw.ScanSSID(); //扫描SSID
    
    
                Thread.Sleep(5000);
    
                mw.ssidWantCon = "hw-ap";
                WIFISSID ws = mw.ssids.Find(mw.find_Ssid_from_ssidList); //查找目标WIFI
    
                ws.wlanInterface.WlanConnectionNotification += MyWifi.WlanIface_WlanConnectionNotification;
    
                mw.ConnectToSSID(ws, "qinglianyun");//连接
    
                Console.ReadKey();
            }
    
    
          
    
        }
    }

    OK,你可以看到我的Main() 里面,就只是搜索和连接WIFI而已。 在连接WIFI时,程序被异常中断。当程序在 Main中执行 

       mw.ConnectToSSID(ws, "qinglianyun"); 

    在 ConnectToSSID()方法中执行  

    bool success = ssid.wlanInterface.ConnectSynchronously(Wlan.WlanConnectionMode.Profile, Wlan.Dot11BssType.Any, profileName, 15000);

     系统出现异常, 

    提示 

    System.ComponentModel.Win32Exception
      HResult=0x80004005
      Message=参数错误。
      Source=ManagedWifi
      StackTrace:
       在 NativeWifi.WlanClient.WlanInterface.ConnectSynchronously(WlanConnectionMode connectionMode, Dot11BssType bssType, String profile, Int32 connectTimeout)
       在 ConsoleApp_WIFI.MyWifi.ConnectToSSID(WIFISSID ssid, String key) 在 C:\Users\dgl\Documents\Code-Project\c#proj\military-proj\ConsoleApp_WIFI\ConsoleApp_WIFI\wifi.cs 中: 第 118 行
       在 ConsoleApp_WIFI.Program.Main(String[] args) 在 C:\Users\dgl\Documents\Code-Project\c#proj\military-proj\ConsoleApp_WIFI\ConsoleApp_WIFI\Program.cs 中: 第 29 行


    我不知道为什么会报这样的错, 我检查了参数,没有问题。求教大神,如何解决这个问题呢? 


    2018年10月25日 4:02

答案

  • 你好,

    由于ManageWifi是一个三方的包,我建议找三方的开发人员,或者相关的技术支持。 


    Best regards,

    Zhanglong


    MSDN Community Support
    Please remember to click "Mark as Answer" the responses that resolved your issue, and to click "Unmark as Answer" if not. This can be beneficial to other community members reading this thread. If you have any compliments or complaints to MSDN Support, feel free to contact MSDNFSF@microsoft.com.

    • 已标记为答案 dgl-victory 2018年10月30日 10:18
    2018年10月26日 5:41

全部回复

  • 你好,

    由于ManageWifi是一个三方的包,我建议找三方的开发人员,或者相关的技术支持。 


    Best regards,

    Zhanglong


    MSDN Community Support
    Please remember to click "Mark as Answer" the responses that resolved your issue, and to click "Unmark as Answer" if not. This can be beneficial to other community members reading this thread. If you have any compliments or complaints to MSDN Support, feel free to contact MSDNFSF@microsoft.com.

    • 已标记为答案 dgl-victory 2018年10月30日 10:18
    2018年10月26日 5:41
  • 非常感谢你的回答,问题已经解决
    2018年10月30日 10:17