日期:2014-05-18  浏览次数:21209 次

c#实现vpn控制2
基于c#实现vpn控制1中类VPNHelper剩余方法如下:
//创建或更新一个VPN连接(指定VPN名称,及IP)
public void CreateOrUpdateVPN(string updateVPNname,string updateVPNip)
{
  RasDialer dialer = new RasDialer();
  RasPhoneBook allUsersPhoneBook = new RasPhoneBook();
  allUsersPhoneBook.Open();
  // 如果已经该名称的VPN已经存在,则更新这个VPN服务器地址
  if (allUsersPhoneBook.Entries.Contains(updateVPNname)){
   allUsersPhoneBook.Entries[updateVPNname].PhoneNumber = updateVPNip;
  // 不管当前VPN是否连接,服务器地址的更新总能成功,如果正在连接,则需要VPN重启后才能起作用
   allUsersPhoneBook.Entries[updateVPNname].Update();              
  }// 创建一个新VPN
  else{
RasEntry entry = RasEntry.CreateVpnEntry(updateVPNname, updateVPNip, RasVpnStrategy.PptpFirst, RasDevice.GetDeviceByName("(PPTP)", RasDeviceType.Vpn));
  allUsersPhoneBook.Entries.Add(entry);
  dialer.EntryName = updateVPNname;
  dialer.PhoneBookPath = RasPhoneBook.GetPhoneBookPath(RasPhoneBookType.AllUsers);              
  }
}
    //删除指定名称的VPN
    //如果VPN正在运行,一样会在电话本里删除,但是不会断开连接,所以,最好是先断开连接,再进行删除操作
public void TryDeleteVPN(string delVpnName){
   RasDialer dialer = new RasDialer();
   RasPhoneBook allUsersPhoneBook = new RasPhoneBook();
   allUsersPhoneBook.Open();
   if (allUsersPhoneBook.Entries.Contains(delVpnName)){
       allUsersPhoneBook.Entries.Remove(delVpnName);
   }
}
        //获取当前正在连接中的VPN名称
        public List<string> GetCurrentConnectingVPNNames()
        {
            List<string> ConnectingVPNList = new List<string>();
            Process proIP = new Process();
            proIP.StartInfo.FileName = "cmd.exe ";
            proIP.StartInfo.UseShellExecute = false;
            proIP.StartInfo.RedirectStandardInput = true;
            proIP.StartInfo.RedirectStandardOutput = true;
            proIP.StartInfo.RedirectStandardError = true;
            proIP.StartInfo.CreateNoWindow = true;//不显示cmd窗口
            proIP.Start();
            proIP.StandardInput.WriteLine(RasDialFileName);
            proIP.StandardInput.WriteLine("exit");
            // 命令行运行结果
            string strResult = proIP.StandardOutput.ReadToEnd();
            proIP.Close();
            // 用正则表达式匹配命令行结果,只限于简体中文系统哦^_^
            Regex regger = new Regex("(?<=已连接\r\n)(.*\n)*(?=命令已完成)", RegexOptions.Multiline);
            // 如果匹配,则说有正在连接的VPN
            if (regger.IsMatch(strResult))
   &n