日前,因需要使用ADSL断线重连以获取新IP,来实现某些功能,特写了一Windows service来实现该功能,在网上找了一些ADSL操作类,如调用DllImport("Rasapi32.dll")的RAS类,只能在XP下操作,在WIN7下无效,后改采用DotRas for Win7来实现,网上的DEMO多是采用DotRas连接VPN的,连接PPPOE的很少,所以折腾了很长一段时间,特此记录.
Step 1:
首先Nuget最新的DotRas for Win7
Step 2:
用code创建一个新的PPPOE链接
/// <summary> /// 创建或更新一个PPPOE连接(指定PPPOE名称) /// </summary> public void CreateOrUpdatePPPOE(string updatePPPOEname) { RasDialer dialer = new RasDialer(); RasPhoneBook allUsersPhoneBook = new RasPhoneBook(); string path = RasPhoneBook.GetPhoneBookPath(RasPhoneBookType.AllUsers); allUsersPhoneBook.Open(path); // 如果已经该名称的PPPOE已经存在,则更新这个PPPOE服务器地址 if (allUsersPhoneBook.Entries.Contains(updatePPPOEname)) { allUsersPhoneBook.Entries[updatePPPOEname].PhoneNumber = " "; // 不管当前PPPOE是否连接,服务器地址的更新总能成功,如果正在连接,则需要PPPOE重启后才能起作用 allUsersPhoneBook.Entries[updatePPPOEname].Update(); } // 创建一个新PPPOE else { string adds = string.Empty; ReadOnlyCollection<RasDevice> readOnlyCollection = RasDevice.GetDevices(); // foreach (var col in readOnlyCollection) // { // adds += col.Name + ":" + col.DeviceType.ToString() + "|||"; // } // _log.Info("Devices are : " + adds); // Find the device that will be used to dial the connection. RasDevice device = RasDevice.GetDevices().Where(o => o.DeviceType == RasDeviceType.PPPoE).First(); RasEntry entry = RasEntry.CreateBroadbandEntry(updatePPPOEname, device); //建立宽带连接Entry entry.PhoneNumber = " "; allUsersPhoneBook.Entries.Add(entry); } }
Step 3:
Connect:
public void Connect(string Connection) { try { CreateOrUpdatePPPOE(Connection); RasDialer dialer = new RasDialer(); dialer.EntryName = Connection; dialer.PhoneNumber = " "; dialer.AllowUseStoredCredentials = true; dialer.PhoneBookPath = RasPhoneBook.GetPhoneBookPath(RasPhoneBookType.AllUsers); dialer.Credentials = new NetworkCredential("username", "password"); dialer.Timeout = 1000; RasHandle myras = dialer.Dial(); while (myras.IsInvalid) { Thread.Sleep(1000); myras = dialer.Dial(); } if (!myras.IsInvalid) { _log.Info("RasDialer Success! " + Convert.ToString(DateTime.Now)); } } catch (Exception ex) { _log.Info("RasDialer error! " + Convert.ToString(DateTime.Now) + Connection + " error is :: " + ex.ToString()); } }