Dinesh Kumar P
Dinesh Kumar P

Reputation: 1168

How to validate dataSource name and PortNumber in Connection String of SqlConnection

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.

Upvotes: 2

Views: 463

Answers (1)

Deepak Bhatia
Deepak Bhatia

Reputation: 6276

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 
}

Upvotes: 1

Related Questions