public bool CheckConection(string connectionString, ref string errorString)
{
SqlConnection sqlConnection = null;
try
{
sqlConnection =
new SqlConnection(connectionString);
sqlConnection.Open();
}
catch (Exception ex)
{
errorString = ex.Message;
return false;
}
finally
{
if (sqlConnection != null)
{
if (sqlConnection.State != ConnectionState.Closed)
{
sqlConnection.Close();
}
sqlConnection.Dispose();
}
}
return true;
}
如果返回false就换服务器
要么就改config文件用xPath找节点修改
XmlDocument xmlDocument = new XmlDocument();
xmlDocument.Load(Application.StartupPath + "\\程序名.exe.Config");
XmlElement xmlNode = xmlDocument.SelectSingleNode("//configuration/connectionStrings/add[@name='ConnectionString']") as XmlElement;
if(xmlNode != null)
{
xmlNode.SetAttribute("connectionString",
@"新连接串");
}
xmlDocument.Save(Application.StartupPath + "\\程序名.exe.Config");
ConfigurationManager.RefreshSection("connectionStrings");
你结合一下吧,我是改的我的代码,可能有不一样的地方,你自己改一下吧。
如果连接的时候找不到服务器只会报错,所以这里用try{}catch{}比较好 catch的时候就去连备份服务器