using System;
using System.Collections.Generic;
using System.Text;
using System.Diagnostics;
using DotRas;
using System.Text.RegularExpressions;
namespace VpnTest
{
public class VPNHelper
{
// 系統路徑 C:\windows\system32\
private static string WinDir = Environment.GetFolderPath(Environment.SpecialFolder.System) + @"";
// rasdial.exe
private static string RasDialFileName = "rasdial.exe";
// VPN路徑 C:\windows\system32\rasdial.exe
private static string VPNPROCESS = WinDir + RasDialFileName;
// VPN地址
public string IPToPing { get; set; }
// VPN名稱
public string VPNName { get; set; }
// VPN用戶名
public string UserName { get; set; }
// VPN密碼
public string PassWord { get; set; }
public VPNHelper()
{
}
public VPNHelper(string _vpnIP, string _vpnName, string _userName, string _passWord)
{
this.IPToPing = _vpnIP;
this.VPNName = _vpnName;
this.UserName = _userName;
this.PassWord = _passWord;
}
//嘗試連接VPN(默認VPN)
public void TryConnectVPN()
{
this.TryConnectVPN(this.VPNName,this.UserName,this.PassWord);
}
//嘗試斷開連接(默認VPN)
public void TryDisConnectVPN()
{
this.TryDisConnectVPN(this.VPNName);
}
//創建或更新一個默認的VPN連接
public void CreateOrUpdateVPN()
{
this.CreateOrUpdateVPN(this.VPNName, this.IPToPing);
}
//嘗試刪除連接(默認VPN)
public void TryDeleteVPN()
{
this.TryDeleteVPN(this.VPNName);
}
//嘗試連接VPN(指定VPN名稱,用戶名,密碼)
public void TryConnectVPN(string connVpnName,string connUserName,string connPassWord)
{
try
{
string args = string.Format("{0} {1} {2}", connVpnName, connUserName, connUserName);
ProcessStartInfo myProcess = new ProcessStartInfo(VPNPROCESS, args);
myProcess.CreateNoWindow = true;
myProcess.UseShellExecute = false;
Process.Start(myProcess);
}
catch (Exception Ex)
{
Debug.Assert(false, Ex.ToString());
}
}
//嘗試斷開VPN(指定VPN名稱)
public void TryDisConnectVPN(string disConnVpnName)
{
try
{
string args = string.Format(@"{0} /d", disConnVpnName);
ProcessStartInfo myProcess = new ProcessStartInfo(VPNPROCESS, args);
myProcess.CreateNoWindow = true;
myProcess.UseShellExecute = false;
Process.Start(myProcess);
}
catch (Exception Ex)
{
Debug.Assert(false, Ex.ToString());
}
}
}
好像是因為那個DotRas.dll沒有返回報錯機制
我最後使用CMD調用rasdial.exe
rasdial connVpnName connUserName connPassWord