因为工作需要,需要用程序来控制×××代理,在google搜了搜,还有不少朋友有同样的需求,但是目前在网上搜索到的解决方案,都还遗留了一些问题。只好自己手动把方案补齐了一下,谈不上原创,大牛们飘过就行。

       先谈谈自己的需求吧,就是针对如图示中的×××连接,咱们至少需要以下四个基本功能。

      1.新建一个×××

      2.修改指定名字×××的主机IP地址

      3.监视当前连接状态

      4.删除指定名称的×××

   直接上代码吧,这里面引用了【DotRas.dll大家可以到官网http://dotras.codeplex.com/ 下载

using System;
using System.Collections.Generic;
using System.Text;
using System.Diagnostics;
using DotRas;
using System.Text.RegularExpressions;
namespace XXX
{
    public class ×××Helper
    {
        // 系统路径 C:\windows\system32\
        private static string WinDir =Environment.GetFolderPath(Environment.SpecialFolder.System) + @"";
        //rasdial.exe
        private static stringRasDialFileName = "rasdial.exe";
        //×××路径 C:\windows\system32\rasdial.exe
        private static string×××PROCESS = WinDir + RasDialFileName;
        //×××地址
        public string IPToPing { get;set; }
        //×××名称
        public string ×××Name { get;set; }
        //×××用户名
        public string UserName { get;set; }
        //×××密码
        public string PassWord { get;set; }

        public ×××Helper()
        {
        }
        ///<summary>
        /// 带参构造函数
        /// </summary>
        /// <paramname="_***IP"></param>
        /// <paramname="_***Name"></param>
        /// <paramname="_userName"></param>
        /// <paramname="_passWord"></param>
        public ×××Helper(string _***IP,string _***Name, string _userName, string _passWord)
        {
            this.IPToPing= _***IP;
            this.×××Name= _***Name;
            this.UserName= _userName;
            this.PassWord= _passWord;
        }
        ///<summary>
        /// 尝试连接×××(默认×××)
        /// </summary>
        ///<returns></returns>
        public void TryConnect×××()
        {
            this.TryConnect×××(this.×××Name,this.UserName,this.PassWord);
        }
        ///<summary>
        /// 尝试断开连接(默认×××)
        /// </summary>
        ///<returns></returns>
        public void TryDisConnect×××()
        {
            this.TryDisConnect×××(this.×××Name);
        }
        ///<summary>
        /// 创建或更新一个默认的×××连接
        /// </summary>
        public void CreateOrUpdate×××()
        {
            this.CreateOrUpdate×××(this.×××Name,this.IPToPing);
        }
        ///<summary>
        /// 尝试删除连接(默认×××)
        /// </summary>
        ///<returns></returns>
        public void TryDelete×××()
        {
            this.TryDelete×××(this.×××Name);
        }
        /// <summary>
        /// 尝试连接×××(指定×××名称,用户名,密码)
        /// </summary>
        ///<returns></returns>
        public voidTryConnect×××(string conn***Name,string connUserName,string connPassWord)
        {
            try
            {
                stringargs = string.Format("{0} {1} {2}", conn***Name, connUserName,connUserName);
                ProcessStartInfomyProcess = new ProcessStartInfo(×××PROCESS, args);
                myProcess.CreateNoWindow= true;
                myProcess.UseShellExecute= false;
                Process.Start(myProcess);
            }
            catch(Exception Ex)
            {
                Debug.Assert(false,Ex.ToString());
            }
        }
        ///<summary>
        /// 尝试断开×××(指定×××名称)
        /// </summary>
        ///<returns></returns>
        public void TryDisConnect×××(stringdisConn***Name)
        {
            try
            {
                stringargs = string.Format(@"{0} /d", disConn***Name);
                ProcessStartInfomyProcess = new ProcessStartInfo(×××PROCESS, args);
                myProcess.CreateNoWindow= true;
                myProcess.UseShellExecute= false;
                Process.Start(myProcess);
   
            }
            catch(Exception Ex)
            {
                Debug.Assert(false,Ex.ToString());
            }
        }
        ///<summary>
        /// 创建或更新一个×××连接(指定×××名称,及IP)
        /// </summary>
        public voidCreateOrUpdate×××(string update×××name,string update×××ip)
        {
            RasDialerdialer = new RasDialer();
            RasPhoneBookallUsersPhoneBook = new RasPhoneBook();
            allUsersPhoneBook.Open();
            //如果已经该名称的×××已经存在,则更新这个×××服务器地址
            if(allUsersPhoneBook.Entries.Contains(update×××name))
            {
                allUsersPhoneBook.Entries[update×××name].PhoneNumber= update×××ip;
                //不管当前×××是否连接,服务器地址的更新总能成功,如果正在连接,则需要×××重启后才能起作用
                allUsersPhoneBook.Entries[update×××name].Update();               
            }
            // 创建一个新×××
            else
            {
                RasEntryentry = RasEntry.Create***Entry(update×××name, update×××ip,Ras***Strategy.PptpFirst, RasDevice.GetDeviceByName("(PPTP)",RasDeviceType.***));
                allUsersPhoneBook.Entries.Add(entry);
                dialer.EntryName= update×××name;
                dialer.PhoneBookPath=RasPhoneBook.GetPhoneBookPath(RasPhoneBookType.AllUsers);               
            }
        }
        ///<summary>
        /// 删除指定名称的×××
        /// 如果×××正在运行,一样会在电话本里删除,但是不会断开连接,所以,最好是先断开连接,再进行删除操作
        /// </summary>
        /// <paramname="del***Name"></param>
        public void TryDelete×××(stringdel***Name)
        {
            RasDialerdialer = new RasDialer();
            RasPhoneBookallUsersPhoneBook = new RasPhoneBook();
            allUsersPhoneBook.Open();
            if(allUsersPhoneBook.Entries.Contains(del***Name))
            {
                allUsersPhoneBook.Entries.Remove(del***Name);
            }
        }
        ///<summary>
        /// 获取当前正在连接中的×××名称
        /// </summary>
        public List<string>GetCurrentConnecting×××Names()
        {
            List<string>Connecting×××List = new List<string>();
            ProcessproIP = 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");
            //命令行运行结果
            stringstrResult = proIP.StandardOutput.ReadToEnd();
            proIP.Close();
            //用正则表达式匹配命令行结果,只限于简体中文系统哦^_^
            Regexregger = new Regex("(?<=已连接\r\n)(.*\n)*(?=命令已完成)", RegexOptions.Multiline);
            //如果匹配,则说有正在连接的×××
            if(regger.IsMatch(strResult))
            {
                string[]list = regger.Match(strResult).Value.ToString().Split('\n');
                for(intindex = 0 ; index < list.Length;index++)
                {
                    if(list[index]!=string.Empty)
                    Connecting×××List.Add(list[index].Replace("\r",""));
                }
            }
            // 没有正在连接的×××,则直接返回一个空List<string>
            returnConnecting×××List;
        }
    }
}

注:该类可以方便的对×××进行【增】,【删】,【改】,【连接】,【断开】操作,在操作前后可以用GetCurrentConnecting×××Names方法来得到正在使用中的×××名称列表,这样一来,可以轻松判断【连接】或【断开】是否成功执行。