首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > .NET > C# >

用c#实现建立一个VPN拨号连接并自动拨号解决方案

2012-04-28 
用c#实现建立一个VPN拨号连接并自动拨号我过些资料,说用RAS库里的RasSetEntryProperties方法可以实现。我写

用c#实现建立一个VPN拨号连接并自动拨号
我过些资料,说用RAS库里的RasSetEntryProperties方法可以实现。我写了一个用C#调用rasapi32.dll方法如下:
  [DllImport("rasapi32.dll", CharSet = CharSet.Auto)]
  public extern static int RasSetEntryProperties(
  string phonebook,
  string entry,
  RasEntry rasentry,
  int entryinfosize, 
  int deviceinfo, 
  int deviceinfosize
  );
RasEntry结构定义如下:
  public struct RasEntry
  {
  public int dwSize;
  public int dwfOptions;
  public int dwCountry;
  public int dwCountryCode;
  public byte szAreaCode;
  public byte szLocalPhoneNumber;
  public int dwalternateOffset;
  public RasIpAddr ipaddr;
  public RasIpAddr ipaddrDns;
  public RasIpAddr ipaddrDnsAlt;
  public RasIpAddr ipaddrWins;
  public RasIpAddr ipaddrWinsAlt;
  public int dwFrameSize;
  public int dwfNetProtocols;
  public int dwFramingProtocol;
  public byte szScript;
  public byte szAutodialDll;
  public byte szAutodialFunc;
  public byte szDeviceType;
  public byte szDeviceName;
  public byte szX25PadType;
  public byte szX25Address;
  public byte szX25Facilities;
  public byte szX25UserData;
  public int dwChannels;
  public int dwReserved1;
  public int dwReserved2;
  public int dwSubEntries;
  public int dwDialMode;
  public int dwDialExtraPercent;
  public int dwDialExtraSampleSeconds;
  public int dwHangUpExtraPercent;
  public int dwHangUpExtraSampleSeconds;
  public int dwIdleDisconnectSeconds;
  public int dwType;
  public int dwEncryptionType;
  public int dwCustomAuthKey;
  public GUID guidId;
  public byte szCustomDialDll;
  public int dwVpnStrategy;
  public int dwfOptions2;
  public int dwfOptions3;
  public byte szDnsSuffix;
  public int dwTcpWindowSize;
  public byte szPrerequisitePbk;
  public byte szPrerequesiteEntry;
  public int dwRedialCount;
  public int dwRedialPause;
  }
调用方法代码如下:
  RasEntry re = new RasEntry();
  re.dwSize = Marshal.SizeOf(typeof(RasEntry));
  re.dwCountryCode = 86;
  re.dwDialExtraPercent = 75;
  re.dwDialExtraSampleSeconds = 120;
  re.dwDialMode = 1;
  re.dwEncryptionType = 3;
  re.dwfNetProtocols = 4;
  re.dwfOptions = 1024262928;
  re.dwfOptions2 = 367;
  re.dwFramingProtocol = 1;
  re.dwHangUpExtraPercent = 10;
  re.dwHangUpExtraSampleSeconds = 120;
  re.dwRedialCount = 3;
  re.dwRedialPause = 60;
  re.dwType = 5;
  re.szAreaCode = 10;
  re.szLocalPhoneNumber = 128;
  re.szScript = 259;
  re.szAutodialDll = 259;
  re.szAutodialFunc = 259;
  re.szDeviceType = 16;
  re.szDeviceName = 128;
  re.szX25PadType = 32;
  re.szX25Address = 200;
  re.szX25Facilities = 200;


  re.szX25UserData = 200;
  re.szCustomDialDll = 259;
  re.szDnsSuffix = 255;
  re.szPrerequisitePbk = 259;
  re.szPrerequesiteEntry = 256;
  re.ipaddr = new RasIpAddr();
  re.ipaddrDns = new RasIpAddr();
  re.ipaddrDnsAlt = new RasIpAddr();
  re.ipaddrWins = new RasIpAddr();
  re.ipaddrWinsAlt = new RasIpAddr();
  re.guidId = new GUID();
  Ras.RasSetEntryProperties(null, "vpn", re, Marshal.SizeOf(typeof(RasEntry)), 0, 0);
编译可以通过,但是运行时出错,提示“尝试读取或写入受保护的内存。这通常指示其他内存已损坏。”
请高手指教是哪里出错了,或告诉一个其他的实现方法。谢谢了

[解决办法]
可能结构没对 我有源码 要留下邮箱 代码太长
[解决办法]

C# code
using System;using System.Collections.Generic;using System.Text;using System.Diagnostics;using DotRas;using System.Net;namespace UpLoadTest{    public class VPN    {        private static string WinDir = Environment.GetFolderPath(Environment.SpecialFolder.System);        private static string fileName = @"\rasdial.exe";//@"\rasphone.exe ";        private static string VPNPROCESS = WinDir + fileName;       //private string _VPNConnectionName = "";        private string _IPToPing = "";        private bool _isConnected = false;        public bool IsConnected        {            get { return _isConnected; }        }        public string IPToPing        {            get { return System.Configuration.ConfigurationSettings.AppSettings["serverIp"].ToString(); }        }        public string VPNConnectionName        {            get { return System.Configuration.ConfigurationSettings.AppSettings["vpnName"].ToString(); }            }        public string UserName        {            get { return System.Configuration.ConfigurationSettings.AppSettings["userName"].ToString(); }        }        public string Password        {            get            {                return System.Configuration.ConfigurationSettings.AppSettings["password"].ToString();            }        }        public static bool TestConnection()        {            VPN vpn = new VPN();//为了以后更多属性,其实现在完全可以不要            bool RV = false;            try            {                System.Net.NetworkInformation.Ping ping = new System.Net.NetworkInformation.Ping();                if (ping.Send(vpn.IPToPing).Status == System.Net.NetworkInformation.IPStatus.Success)                {                    RV = true;                }                else                {                    RV = false;                }                ping = null;            }            catch (Exception Ex)            {                Debug.Assert(false, Ex.ToString());                RV = false;            }            return RV;        }        public static bool ConnectToVPN()        {            VPN vpn = new VPN();            bool RV = false;            try            {                               string args = string.Format("{0} {1} {2}",vpn.VPNConnectionName,vpn.UserName,vpn.Password);                ProcessStartInfo myProcess = new ProcessStartInfo(VPNPROCESS,args);                //System.Security.SecureString secretString = new System.Security.SecureString();                //foreach (char c in vpn.Password)                //    secretString.AppendChar(c);                //myProcess.Arguments = vpn.VPNConnectionName;                //myProcess.UserName = vpn.UserName;                //myProcess.Password = secretString;                //myProcess.Domain = "@ADServer.Local";                myProcess.CreateNoWindow = true;                myProcess.UseShellExecute = false;                                          //Process.Start(VPNPROCESS, );                             //Process.Start(VPNPROCESS, " -d " + vpn.VPNConnectionName);                Process.Start(myProcess);                //System.Windows.Forms.Application.DoEvents();                //System.Threading.Thread.Sleep(2000);               // System.Windows.Forms.Application.DoEvents();                RV = true;            }            catch (Exception Ex)            {                Debug.Assert(false, Ex.ToString());                RV = false;            }            return RV;        }        public static bool DisconnectFromVPN()        {            VPN vpn = new VPN();            bool RV = false;            try            {                //System.Diagnostics.Process.Start(VPNPROCESS, " -h " + vpn.VPNConnectionName);                //System.Diagnostics.Process.Start(VPNPROCESS, string.Format(@"{0} /d",vpn.VPNConnectionName));                string args = string.Format(@"{0} /d", vpn.VPNConnectionName);                ProcessStartInfo myProcess = new ProcessStartInfo(VPNPROCESS, args);                myProcess.CreateNoWindow = true;                myProcess.UseShellExecute = false;                System.Diagnostics.Process.Start(myProcess);                //System.Windows.Forms.Application.DoEvents();                //System.Threading.Thread.Sleep(2000);                //System.Windows.Forms.Application.DoEvents();                RV = true;            }            catch (Exception Ex)            {                Debug.Assert(false, Ex.ToString());                RV = false;            }            return RV;        }        public static void CreateVPN()        {            VPN vpn = new VPN();            DotRas.RasDialer dialer = new DotRas.RasDialer();            DotRas.RasPhoneBook allUsersPhoneBook = new DotRas.RasPhoneBook();            allUsersPhoneBook.Open();            if (allUsersPhoneBook.Entries.Contains(vpn.VPNConnectionName))            {                return;            }            RasEntry entry = RasEntry.CreateVpnEntry(vpn.VPNConnectionName, vpn.IPToPing, RasVpnStrategy.PptpFirst, RasDevice.GetDeviceByName("(PPTP)", RasDeviceType.Vpn));            allUsersPhoneBook.Entries.Add(entry);            dialer.EntryName = vpn.VPNConnectionName;            dialer.PhoneBookPath = RasPhoneBook.GetPhoneBookPath(RasPhoneBookType.AllUsers);            try            {                dialer.DialAsync(new NetworkCredential(vpn.UserName, vpn.Password));            }            catch (Exception)            {                return;            }        }        public VPN()        {        }    }} 

热点排行