2

Please tell how to validate dataSource name and PortNumber in Connection String of SqlConnection. Connection state changes to Open, even I donot give any value for dataSource. Like the code below..

var Connection = new SqlConnection("Data Source=;Trusted_Connection=True");
try
{
    Connection.Open();
    MessageBox.Show("Connection Succeeded");
}

My requirement is I need to validate the Data Source name and Port Number that are entered by EndUser.

Dinesh Kumar P
  • 1,128
  • 2
  • 18
  • 32
  • If no data source and port number is defined then an SQLException is thrown at Connection.Open, so do you want to validate connection string before opening connection – Deepak Bhatia Oct 25 '13 at 10:54

1 Answers1

1

For offline validation, use SqlConnectionStringBuilder to parse it...

SqlConnectionStringBuilder myconBuilder = new SqlConnectionStringBuilder();
myconBuilder.ConnectionString = "Data Source=;Trusted_Connection=True";  //Throws exception if garbage connection string like 'abcd' is supplied
if (string.IsNullOrWhiteSpace(myconBuilder.DataSource))
{ 
    //Throw exception that data source specified is blank 
}
Deepak Bhatia
  • 6,230
  • 2
  • 24
  • 58