110,538
社区成员
发帖
与我相关
我的任务
分享
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Runtime.InteropServices;
using System.Net;
using System.Text.RegularExpressions;
using System.Threading;
using System.Net.NetworkInformation;
using System.Data.SqlClient;
namespace ConnectState
{
public partial class frmConnectTest : Form
{
[Flags]
enum ConnectionState : int
{
INTERNET_CONNECTION_MODEM = 0x1,
INTERNET_CONNECTION_LAN = 0x2,
INTERNET_CONNECTION_PROXY = 0x4,
INTERNET_RAS_INSTALLED = 0x10,
INTERNET_CONNECTION_OFFLINE = 0x20,
INTERNET_CONNECTION_CONFIGURED = 0x40
}
[DllImport("wininet", CharSet = CharSet.Auto)]
static extern bool InternetGetConnectedState(ref ConnectionState lpdwFlags, int dwReserved);
static bool IsOffline()
{
ConnectionState state = 0;
InternetGetConnectedState(ref state, 0);
if (((int)ConnectionState.INTERNET_CONNECTION_OFFLINE & (int)state) != 0)
{
return true;
}
return false;
}
public frmConnectTest()
{
InitializeComponent();
}
private void frmConnectTest_Load(object sender, EventArgs e)
{
}
string _server = string.Empty;
string _dbName = string.Empty;
string _pwd = string.Empty;
string _uid = string.Empty;
private void btnTest_Click(object sender, EventArgs e)
{
string host = string.Empty;
bool isIPAddress = false;
IPAddress ip = null;
_server = txtServer.Text.Trim();
_dbName = txtDB.Text.Trim();
_uid = txtUid.Text.Trim();
_pwd = txtPwd.Text.Trim();
if (_server.Length == 0 || _dbName.Length == 0 || _uid.Length == 0)
{
MessageBox.Show("服务器、数据库、用户名不能为空,请填写.");
return;
}
if (IsOffline())
{
if(MessageBox.Show("现在连接处于离线状态,继续测试吗?")== DialogResult.Cancel)
return;
}
bool isLocal = Regex.IsMatch(_server.ToLower(), @"^.|(local)");
isIPAddress = Regex.IsMatch(_server, @"^(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])\.(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])\.(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])\.(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])$");
// 指定服务器是本机
if (isLocal)
{
try
{
ip = Dns.GetHostEntry(Dns.GetHostName()).AddressList[0];
}
catch (Exception ex)
{
MessageBox.Show(string.Format("Dns 错误:{0}", ex.Message));
return;
}
}
else if (isIPAddress) // 指定IP
{
ip = IPAddress.Parse(_server);
}
else // 指定服务器名称
{
try
{
ip = Dns.GetHostEntry(_server).AddressList[0];
}
catch (Exception ex)
{
MessageBox.Show(string.Format("Dns 错误:{0}", ex.Message));
return;
}
}
ParameterizedThreadStart thStart = new ParameterizedThreadStart(PingTest);
thStart.BeginInvoke(ip, AsyncCallbackMethod, null);
btnTest.Enabled = false;
tssPro.Text = string.Format("正在测试与服务器{0}连接...", _server);
}
private void AsyncCallbackMethod(IAsyncResult ar)
{
// 服务器ping测试通过后,检测Sql Server的连接
if (success)
{
DateTime? now = null;
tssPro.Text = string.Format("连接服务器{0}正常,正在测试与数据库{1}连接...", _server, _dbName);
string conStr = string.Format("server={0};database={1};uid={2};pwd={3};Connection Timeout=5;", _server, _dbName, _uid, _pwd);
SqlConnection con = new SqlConnection(conStr);
try
{
now = DateTime.Now;
con.Open();
con.Close();
tssPro.Text = "";
MessageBox.Show("测试连接成功");
}
catch (Exception ex)
{
TimeSpan ts = DateTime.Now.Subtract(now.Value);
MessageBox.Show(string.Format("无法连接数据库:{0}\n{1}\n耗时:{2}秒", _dbName,ex.Message,ts.Seconds));
}
}
else
{
tssPro.Text = "";
MessageBox.Show(string.Format("找不到服务器:{0}",_server));
}
}
private bool success = false;
/// <summary>
/// Ping 测试
/// </summary>
/// <param name="ipAddress"></param>
private void PingTest(object ipAddress)
{
IPAddress ip = (IPAddress)ipAddress;
PingOptions options = new PingOptions(128, true);
Ping ping = new Ping();
byte[] data = new byte[32];
//ping 4 次
for (int i = 0; i < 4; i++)
{
PingReply reply = ping.Send(ip, 1000, data, options);
if (reply != null)
{
switch (reply.Status)
{
case IPStatus.Success:
success = true;
break;
case IPStatus.TimedOut:
break;
default:
break;
}
}
}
}
}
}