最近要用程序来不断的连接VPN(为什么要这样就不讨论了),开始用的是如下代码:

    public static bool ADSL()
         {
             bool flag = true;
             do
             {
                 Console.WriteLine(DateTime.Now.ToString("yyyy-MM-dd HH:mm") + " 重新拨号...");
                 Disconnect(ConfigurationManager.AppSettings["AdslName"]);
                 Thread.Sleep();
                 Connect(ConfigurationManager.AppSettings["AdslName"], ConfigurationManager.AppSettings["Adsl"], ConfigurationManager.AppSettings["Pwd"]);
                 Thread.Sleep();
                 flag = PingIpOrDomainName("www.baidu.com");
             } while (!flag);
             return flag;
         }
         public static bool PingIpOrDomainName(string strIpOrDName)
         {
             try
             {
                 Ping objPingSender = new Ping();
                 PingOptions objPinOptions = new PingOptions();
                 objPinOptions.DontFragment = true;
                 string data = "";
                 byte[] buffer = Encoding.UTF8.GetBytes(data);
                 ;
                 PingReply objPinReply = objPingSender.Send(strIpOrDName, intTimeout, buffer, objPinOptions);
                 string strInfo = objPinReply.Status.ToString();
                 if (strInfo == "Success")
                 {
                     return true;
                 }
                 else
                 {
                     return false;
                 }
             }
             catch (Exception)
             {
                 return false;
             }
         }
         public static string InvokeCmd(string cmdArgs)
         {
             Process p = new Process();
             p.StartInfo.FileName = "cmd.exe";
             p.StartInfo.UseShellExecute = false;
             p.StartInfo.RedirectStandardInput = true;
             p.StartInfo.RedirectStandardOutput = true;
             p.StartInfo.RedirectStandardError = true;
             p.StartInfo.CreateNoWindow = true;
             p.Start();
             p.StandardInput.WriteLine(cmdArgs);
             p.StandardInput.WriteLine("exit");
             return p.StandardOutput.ReadToEnd();
         }
         public static void Connect(string connectionName, string user, string pass)
         {
             string arg = string.Format("rasdial \"{0}\" {1} {2}", connectionName, user, pass);
             InvokeCmd(arg);
         }
         public static void Disconnect(string connectionName)
         {
             string arg = string.Format("rasdial \"{0}\" /disconnect", connectionName);
             InvokeCmd(arg);
         }

  这个类在平时也是能用,问题就在我需要不断的循环(连接-执行业务-断开-连接-执行业务-断开),而且频率还很高。在连接以后ping下baidu.com是否连接成功!但很多次都提示ping不上baidu.com,平时用的时候ping不上,就重新连接,倒也是可以的。

  但最近需要连VPN,决定重新写这些方法,在网上啪啦啪啦好久,用上了DotRas:http://dotras.codeplex.com/

  并且根据Demo,写了个辅助类DialerHelper:

     public class DialerHelper
     {
         public RasHandle handle { get; set; }
         public string VPNIP { get; set; }
         // VPN名称
         public string EntryName { get; set; }
         // VPN用户名
         public string UserName { get; set; }
         // VPN密码
         public string PassWord { get; set; }
         private RasPhoneBook _phoneBook;

         public RasPhoneBook PhoneBook
         {
             get
             {
                 if (_phoneBook == null)
                     _phoneBook = new RasPhoneBook();
                 return _phoneBook;
             }
             set { _phoneBook = value; }
         }
         private RasDialer _dialer;
         public RasDialer Dialer
         {
             get
             {
                 if (_dialer == null)
                     _dialer = new RasDialer();
                 return _dialer;
             }
             set { _dialer = value; }
         }

         public DialerHelper()
         {
         }

         /// <summary>
         /// 带参构造函数
         /// </summary>
         /// <param name="_vpnIP"></param>
         /// <param name="_vpnName"></param>
         /// <param name="_userName"></param>
         /// <param name="_passWord"></param>
         public DialerHelper(string _vpnIP, string _entryName, string _userName, string _passWord)
         {
             this.VPNIP = _vpnIP;
             this.EntryName = _entryName;
             this.UserName = _userName;
             this.PassWord = _passWord;
         }

         /// <summary>
         /// 创建VPN
         /// </summary>
         public void CreateEntry()
         {
             CreateEntry(this.EntryName, VPNIP);
         }
         /// <summary>
         /// 创建VPN
         /// </summary>
         /// <param name="VPNName"></param>
         /// <param name="VPNIP"></param>
         public void CreateEntry(string VPNName,string VPNIP)
         {
             // This opens the phonebook so it can be used. Different overloads here will determine where the phonebook is opened/created.
             this.PhoneBook.Open();

             // Create the entry that will be used by the dialer to dial the connection. Entries can be created manually, however the static methods on
             // the RasEntry class shown below contain default information matching that what is set by Windows for each platform.
             RasEntry entry = RasEntry.CreateVpnEntry(VPNName, IPAddress.Loopback.ToString(), RasVpnStrategy.Default,
                 RasDevice.GetDeviceByName("(PPTP)", RasDeviceType.Vpn));

             entry.PhoneNumber = VPNIP;

             // Add the new entry to the phone book.
             this.PhoneBook.Entries.Add(entry);

         }

         /// <summary>
         /// 连接
         /// </summary>
         public bool ConnectEntry()
         {
             return ConnectEntry(UserName, PassWord);
         }
         /// <summary>
         /// 连接
         /// </summary>
         /// <param name="sender">The object that raised the event.</param>
         /// <param name="e">An <see cref="System.EventArgs"/> containing event data.</param>
         private bool ConnectEntry(string _userName, string _passWord)
         {

             // This button will be used to dial the connection.
             this.Dialer.EntryName = EntryName;
             this.Dialer.PhoneBookPath = RasPhoneBook.GetPhoneBookPath(RasPhoneBookType.AllUsers);

             try
             {
                 // Set the credentials the dialer should use.
                 this.Dialer.Credentials = new NetworkCredential(UserName, PassWord);

                 // NOTE: The entry MUST be in the phone book before the connection can be dialed.
                 // Begin dialing the connection; this will raise events from the dialer instance.
                  handle = this.Dialer.Dial();
                  return true;
             }
             catch (Exception ex)
             {
                 return false;
                 //this.StatusTextBox.AppendText(ex.ToString());
             }
         }

         /// <summary>
         /// 连接
         /// </summary>
         public void ConnectEntryAsync()
         {
             ConnectEntryAsync(UserName, PassWord);
         }
         /// <summary>
         /// 连接
         /// </summary>
         /// <param name="sender">The object that raised the event.</param>
         /// <param name="e">An <see cref="System.EventArgs"/> containing event data.</param>
         private void ConnectEntryAsync(string _userName, string _passWord)
         {

             // This button will be used to dial the connection.
             this.Dialer.EntryName = EntryName;
             this.Dialer.PhoneBookPath = RasPhoneBook.GetPhoneBookPath(RasPhoneBookType.AllUsers);

             try
             {
                 // Set the credentials the dialer should use.
                 this.Dialer.Credentials = new NetworkCredential(UserName, PassWord);

                 // NOTE: The entry MUST be in the phone book before the connection can be dialed.
                 // Begin dialing the connection; this will raise events from the dialer instance.
                 handle = this.Dialer.DialAsync();
             }
             catch (Exception ex)
             {
                 //this.StatusTextBox.AppendText(ex.ToString());
             }
         }
         /// <summary>
         ///
         /// </summary>
         public void DisconnectEntry()
         {
             if (this.Dialer.IsBusy)
             {
                 // The connection attempt has not been completed, cancel the attempt.
                 this.Dialer.DialAsyncCancel();
             }
             else
             {
                 // The connection attempt has completed, attempt to find the connection in the active connections.
                 RasConnection connection = RasConnection.GetActiveConnectionByHandle(this.handle);
                 if (connection != null)
                 {
                     // The connection has been found, disconnect it.
                     connection.HangUp();
                 }
             }
         }
     }

用DotRas来连接VPN网络的更多相关文章

  1. Windows 8 应用商店无法连接到网络的终极完美解决方案

    当你看到以下几个步骤的时候,你可能会不以为然,因为你已经试过了,还是没成功,依然提示"你的电脑没有连接到Internet或者现在无法使用Windows应用商店,要使用Windows应用商店, ...

  2. 解决连接VPN后无法上网问题

    解决连接VPN后无法上网问题 VPN的英文全称是“Virtual Private Network”,翻译过来就是“虚拟专用网络”.顾名思义,虚拟专用网络可以把它理解成是虚拟出来的企业内部专线. 在公司 ...

  3. 如何处理Win7连接vpn时报错789的问题

    [转]VPN错误提示: vpn连接出错789:L2TP连接尝试失败,因为安全层在初始化与远程计算机的协商时遇 (2014-08-11 15:09:10)转载▼标签: it xp连接VPN错误提示: v ...

  4. 【Win10 应用开发】扫描和连接Wi-fi网络

    老周今天带大家去“扫雷”了,别当真,是扫描并连接指定无线网络,时尚一点叫Wi-fi. 所以,今天的任务要求你的设备至少有1张无线网卡,目前老周没看到过有N张无线网卡的设备.像笔记本.平板等设备都可以, ...

  5. 解决OS X系统连接VPN后无法访问内网资源的问题

    该问题是第一次使用OS X系统连接VPN遇到的问题,现象是连接VPN成功,但无法访问公司的内网资源. 主要原因还是VPN设置上的问题,在系统偏好设置中打开VPN连接,里面有个高级设置,如图: 点击高级 ...

  6. 双系统下(Ubuntu + win7)windows 无法连接无线网络

    双系统下(Ubuntu + win7)windows 无法连接无线网络 今天开机登录win7,突然发现无法使用无线网络(WiFi信号标志有个大红叉),于是查看设备驱动,一切正常,这就奇怪了:用Wind ...

  7. linux开机自动连接无线网络

           1.右击无线网络图标的“编辑连接”. 2.在“无线”选项卡里,选择“编辑”. 3.在“无线安全性”选项卡里,输入无线密匙,并选中左下角的“对所有用户可      用”的选项点击应用,会提 ...

  8. 「ubuntu」通过无线网络安装Ubuntu Server,启动系统后如何连接无线网络

    接触Ubuntu系统不久,发现无线网络环境下安装Ubuntu Server一个不太人性化的设计:在安装过程中选择无线网卡,即使用无线网络安装(此时需要选择Wi-Fi网络并输入密码),但系统安装完成重启 ...

  9. 记在centos中连接无线网络的一次过程

    1. 首先, 你的系统要能驱动无限网卡, 要是人品好的话, 系统已经自带了你的网卡的驱动程序. 不然就要先搞定无线网卡的驱动再说. 不然后面的步骤也就没必要了. 2. 看一下你的无线网卡叫什么: iw ...

随机推荐

  1. java web开发中的奇葩事web.xml中context-param中的注释

    同事提交了代码.结果除同事之外,其他人全部编译报错.报错说web.xml中配置的一个bean 没有定义.按照报错提示,各种找,无果. 由于代码全部都是提交到svn主干,之前也没有做过备份,只能一步一步 ...

  2. iOS 错误 之 http请求

     Application Transport Security has blocked a cleartext HTTP (http://) resource load since it is ins ...

  3. jquery 中prop()的使用方法

    1:设置input的选中属性:$('.passenger').find('.is-need-tel').prop('checked',true); 2:获取input是否选中: $('.passeng ...

  4. 才一年,H5的发展就成这样了......

    关于H5的发展,分享几个最近看到的惊人数据和新闻: 1.截至2015,有80%的App将全部或部分基于HTML5.这意味着大部分App的内容都将是以网页的形式呈现,典型的例子包括微信.Facebook ...

  5. JavaSwing JScrollPane的使用

    JavaSwing JScrollPane的使用: 参考:http://duyz.blog.ifeng.com/article/340649.html package com.srie.test; i ...

  6. iOS动画案例(1)

       受人所托,做一个类似于qq账号信息里的一个动画,感觉挺有意思,也没感觉有多难,就开始做了,结果才发现学的数学知识都还给体育老师了,研究了大半天才做出来.    先看一下动画效果:   用到的知识 ...

  7. JDBC 的编程步骤

    1.加载数据库驱动 2.获得数据库连接 3.创建语句 4.执行查询 5.遍历结果集 6.关闭数据库连接 尽量把数据库的连接步骤写成一个单独的java类,使用的时候直接new一个对象, import j ...

  8. 如何让Docker容器随宿主机的启动而自动启动

    使用Docker容器部署服务时,不仅需要让服务随Docker容器的启动而启动,还需要让Docker容器随宿主机的启动而自动启动,为此Docker提供了Docker run的restart参数 #doc ...

  9. es6笔记6^_^generator

    1.简介 Generator函数是一个函数的内部状态的遍历器(也就是说,Generator函数是一个状态机). 形式上,Generator函数是一个普通函数,但是有两个特征. function命令与函 ...

  10. 对于python的__name__="__main__"的含义的理解

    学习python的时候经常会看到python 中__name__ = \'__main__\' 这样的代码,可能很多新手一开始学习的时候都比较疑惑,python 中__name__ = '__main ...