详解C#实现adsl自动拨号连接上网的方法

在网络编程中,有时候会需要重新拨号建立 网络连接(如Ad点击软件通过重新拨号形成有效点击) ,下面介绍两种程序中拨号的方法.

1、最简单的方法:使用RasDial命令

RasDial是Windows自带的命令,使用非常简单。实际使用是可将下面代码保存为一个批处理文件,然后直接运行或在程序里进行调用。

rasdial.exe /disconnect '断开连接

del "C:\Documents and Settings\hyuqin\Cookies\*.*" /Q '清除Cookie

rasdial.exe 连接名 连接账户 连接密码 '重新拨号

2、封装为类,灵活调用

上面提到的方法虽然很简单,但并非标准的实现方法,使用时会受到一些限制,此时最好的办法就是将实现代码封装为类库。下面这个类库是网上一位朋友提供的, 直接调用就行.

1using System;

2using System.Runtime.InteropServices;

3

4public struct RASCONN

5{

6 public int dwSize;

7 public IntPtr hrasconn;

8 [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 257)]

9 public string szEntryName;

10 [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 17)]

11 public string szDeviceType;

12 [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 129)]

13 public string szDeviceName;

14}

15

16[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Auto)]

17public struct RasStats

18{

19 public int dwSize;

20 public int dwBytesXmited;

21 public int dwBytesRcved;

22 public int dwFramesXmited;

23 public int dwFramesRcved;

24 public int dwCrcErr;

25 public int dwTimeoutErr;

26 public int dwAlignmentErr;

27 public int dwHardwareOverrunErr;

28 public int dwFramingErr;

29 public int dwBufferOverrunErr;

30 public int dwCompressionRatioIn;

31 public int dwCompressionRatioOut;

32 public int dwBps;

33 public int dwConnectionDuration;

34}

35

36[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Auto)]

37public struct RasEntryName

38{

39 public int dwSize;

40 //[MarshalAs(UnmanagedType.ByValTStr,SizeConst=(int)RasFieldSizeConstants.RAS_MaxEntryName + 1)]

41 public string szEntryName;

42 //#if WINVER5

43 // public int dwFlags;

44 // [MarshalAs(UnmanagedType.ByValTStr,SizeConst=260+1)]

45 // public string szPhonebookPath;

46 //#endif

47}

48public class RAS

49{

50 [DllImport("Rasapi32.dll", EntryPoint = "RasEnumConnectionsA",

51 SetLastError = true)]

52

53 internal static extern int RasEnumConnections

54 (

55 ref RASCONN lprasconn, // buffer to receive connections data

56 ref int lpcb, // size in bytes of buffer

57 ref int lpcConnections // number of connections written to buffer

58 );

59

60

61 [DllImport("rasapi32.dll", CharSet = CharSet.Auto)]

62 internal static extern uint RasGetConnectionStatistics(

63 IntPtr hRasConn, // handle to the connection

64 [In, Out]RasStats lpStatistics // buffer to receive statistics

65 );

66 [DllImport("rasapi32.dll", CharSet = CharSet.Auto)]

67 public extern static uint RasHangUp(

68 IntPtr hrasconn // handle to the RAS connection to hang up

69 );

70

71 [DllImport("rasapi32.dll", CharSet = CharSet.Auto)]

72 public extern static uint RasEnumEntries(

73 string reserved, // reserved, must be NULL

74 string lpszPhonebook, // pointer to full path and

75 // file name of phone-book file

76 [In, Out]RasEntryName[] lprasentryname, // buffer to receive

77 // phone-book entries

78 ref int lpcb, // size in bytes of buffer

79 out int lpcEntries // number of entries written

80 // to buffer

81 );

82

83 [DllImport("wininet.dll", CharSet = CharSet.Auto)]

84 public extern static int InternetDial(

85 IntPtr hwnd,

86 [In]string lpszConnectoid,

87 uint dwFlags,

88 ref int lpdwConnection,

89 uint dwReserved

90 );

91

92 public RAS()

93 {

94 }

95}

96public enum DEL_CACHE_TYPE //要删除的类型。

97{

98 File,//表示internet临时文件

99 Cookie //表示Cookie

100}

101

102public class RASDisplay

103{

104 [DllImport("wininet.dll", CharSet = CharSet.Auto)]

105 public static extern bool DeleteUrlCacheEntry(

106 DEL_CACHE_TYPE type

107 );

108 private string m_duration;

109 private string m_ConnectionName;

110 private string[] m_ConnectionNames;

111 private double m_TX;

112 private double m_RX;

113 private bool m_connected;

114 private IntPtr m_ConnectedRasHandle;

115

116 RasStats status = new RasStats();

117 public RASDisplay()

118 {

119 m_connected = true;

120

121 RAS lpras = new RAS();

122 RASCONN lprasConn = new RASCONN();

123

124 lprasConn.dwSize = Marshal.SizeOf(typeof(RASCONN));

125 lprasConn.hrasconn = IntPtr.Zero;

126

127 int lpcb = 0;

128 int lpcConnections = 0;

129 int nRet = 0;

130 lpcb = Marshal.SizeOf(typeof(RASCONN));

131

132 nRet = RAS.RasEnumConnections(ref lprasConn, ref lpcb, ref

133 lpcConnections);

134

135 if (nRet != 0)

136 {

137 m_connected = false;

138 return;

139

140 }

141

142 if (lpcConnections > 0)

143 {

144 //for (int i = 0; i < lpcConnections; i++)

145

146 //{

147 RasStats stats = new RasStats();

148

149 m_ConnectedRasHandle = lprasConn.hrasconn;

150 RAS.RasGetConnectionStatistics(lprasConn.hrasconn, stats);

151

152

153 m_ConnectionName = lprasConn.szEntryName;

154

155 int Hours = 0;

156 int Minutes = 0;

157 int Seconds = 0;

158

159 Hours = ((stats.dwConnectionDuration / 1000) / 3600);

160 Minutes = ((stats.dwConnectionDuration / 1000) / 60) - (Hours * 60);

161 Seconds = ((stats.dwConnectionDuration / 1000)) - (Minutes * 60) - (Hours * 3600);

162

163

164 m_duration = Hours + " hours " + Minutes + " minutes " + Seconds + " secs";

165 m_TX = stats.dwBytesXmited;

166 m_RX = stats.dwBytesRcved;

167 //}

168 }

169 else

170 {

171 m_connected = false;

172 }

173

174

175 int lpNames = 1;

176 int entryNameSize = 0;

177 int lpSize = 0;

178 RasEntryName[] names = null;

179

180 entryNameSize = Marshal.SizeOf(typeof(RasEntryName));

181 lpSize = lpNames * entryNameSize;

182

183 names = new RasEntryName[lpNames];

184 names[0].dwSize = entryNameSize;

185

186 uint retval = RAS.RasEnumEntries(null, null, names, ref lpSize, out lpNames);

187

188 //if we have more than one connection, we need to do it again

189 if (lpNames > 1)

190 {

191 names = new RasEntryName[lpNames];

192 for (int i = 0; i < names.Length; i++)

193 {

194 names[i].dwSize = entryNameSize;

195 }

196

197 retval = RAS.RasEnumEntries(null, null, names, ref lpSize, out lpNames);

198

199 }

200 m_ConnectionNames = new string[names.Length];

201

202

203 if (lpNames > 0)

204 {

205 for (int i = 0; i < names.Length; i++)

206 {

207 m_ConnectionNames[i] = names[i].szEntryName;

208 }

209 }

210 }

211

212 public string Duration

213 {

214 get

215 {

216 return m_connected ? m_duration : "";

217 }

218 }

219

220 public string[] Connections

221 {

222 get

223 {

224 return m_ConnectionNames;

225 }

226 }

227

228 public double BytesTransmitted

229 {

230 get

231 {

232 return m_connected ? m_TX : 0;

233 }

234 }

235 public double BytesReceived

236 {

237 get

238 {

239 return m_connected ? m_RX : 0;

240

241 }

242 }

243 public string ConnectionName

244 {

245 get

246 {

247 return m_connected ? m_ConnectionName : "";

248 }

249 }

250 public bool IsConnected

251 {

252 get

253 {

254 return m_connected;

255 }

256 }

257

258 public int Connect(string Connection)

259 {

260 int temp = 0;

261 uint INTERNET_AUTO_DIAL_UNATTENDED = 2;

262 int retVal = RAS.InternetDial(IntPtr.Zero, Connection, INTERNET_AUTO_DIAL_UNATTENDED, ref temp, 0);

263 return retVal;

264 }

265 public void Disconnect()

266 {

267 RAS.RasHangUp(m_ConnectedRasHandle);

268 }

269}

调用方法:

RASDisplay ras = new RASDisplay();

ras.Disconnect();//断开连接

ras.Connect("ADSL");// 重新拨号