本文實例講述了C#.NET獲取撥號連接的寬帶連接方法。分享給大家供大家參考。具體如下:
該代碼直接可以用,我在XP VS2010 NET3.5上測試通過。
首先是ASDL的封裝
class SinASDL{ //ASDL在注冊表中的存放位置,這個是針對WinXP的, //不知道Win7是否是這個,待驗證 private static String _adlskeys = @"RemoteAccess/Profile"; public static String adlskeys { get { return _adlskeys; } } /// <summary> /// 獲取本機的撥號名稱,也就是本機上所有的撥號 /// </summary> /// <returns></returns> public static String[] GetASDLNames() { RegistryKey RegKey = Registry.CurrentUser.OpenSubKey(adlskeys); if (RegKey != null) return RegKey.GetSubKeyNames(); else return null; } private String _asdlname = null; private ProcessWindowStyle _windowstyle = ProcessWindowStyle.Hidden; /// <summary> /// 實例化一個ASDL連接 /// </summary> /// <param name="asdlname">ASDL名稱,如“寬帶連接”</param> /// <param name="username">用戶名</param> /// <param name="password">密碼</param> /// <param name="windowstyle">窗口顯示方式,默認為因此撥號過程</param> public SinASDL(String asdlname, String username = null, String password = null, ProcessWindowStyle windowstyle = ProcessWindowStyle.Hidden) { this.ASDLName = asdlname; this.Username = username; this.Password = password; this.WindowStyle = windowstyle; } /// <summary> /// 撥號名稱 /// </summary> public String ASDLName { get { return this._asdlname; } set { this._asdlname = value; } } /// <summary> /// 撥號進程的窗口方式 /// </summary> public ProcessWindowStyle WindowStyle { get { return this._windowstyle; } set { this._windowstyle = value; } } private String _username = null; //用戶名 private String _password = null; //密碼 /// <summary> /// 用戶名 /// </summary> public String Username { get { return this._username; } set { this._username = value; } } /// <summary> /// 密碼 /// </summary> public String Password { get { return this._password; } set { this._password = value; } } /// <summary> /// 開始撥號 /// </summary> /// <returns>返回撥號進程的返回值</returns> public int Connect() { Process pro = new Process(); pro.StartInfo.FileName = "rasdial.exe"; pro.StartInfo.Arguments = this.ASDLName + " " + this.Username + " " + this.Password; pro.StartInfo.WindowStyle = this.WindowStyle; pro.Start(); pro.WaitForExit(); return pro.ExitCode; } /// <summary> /// 端口連接 /// </summary> /// <returns></returns> public int Disconnect() { Process pro = new Process(); pro.StartInfo.FileName = "rasdial.exe"; pro.StartInfo.Arguments = this.ASDLName + " /DISCONNECT"; pro.StartInfo.WindowStyle = this.WindowStyle; pro.Start(); pro.WaitForExit(); return pro.ExitCode; }}
下面是使用測試:
//SinASDL asdl = new SinASDL("寬帶連接", "08793312221", "123456");//寬帶連接//使用枚舉到的第一個進行撥號SinASDL asdl = new SinASDL(SinASDL.GetASDLNames()[0], "08793312221", "123456", System.Diagnostics.ProcessWindowStyle.Normal);if (asdl.Connect() == 0){ MessageBox.Show("Success");}else{ MessageBox.Show("Fail");}
我自己測試的時候是通過的。
如果電腦上不止一個撥號的,那么你可以用SinASDL.GetASDLNames()進行枚舉。
希望本文所述對大家的C#程序設計有所幫助。
新聞熱點
疑難解答