user123_456
user123_456

Reputation: 5805

How to compare open connection string with connection string from config file

Hi all I want to check if my opened connection is same as the connection string from config file.

I was trying something like this:

if(con.ConnectionString == ConfigurationManager.ConnectionStrings["Con1"].ConnectionString);

The first part is giving me right value and second part should give me the same string.

EDIT: This is my entire connection string as I didn't want to bother you with the details:

if (DateTime.Now.Subtract(lastDBcheck).TotalSeconds > 10 && con.ConnectionString==ConfigurationManager.ConnectionStrings["Con1"].ConnectionString)

Upvotes: 1

Views: 1155

Answers (3)

Mark Byers
Mark Byers

Reputation: 838896

Using == to compare the values of strings is correct in C#.

If your code isn't working it's most likely due to either:

  • The values aren't actually the same (maybe one has extra whitespace or a small change).
  • You are getting an exception.

To avoid the latter case I suggest that you check that your objects are not null before dereferencing them.

var con1 = ConfigurationManager.ConnectionStrings["Con1"];

if (con != null && con1 != null && con.ConnectionString == con1.ConnectionString) {
    // Connection strings are the same.
}

Upvotes: 2

Joanna Derks
Joanna Derks

Reputation: 4063

I think this will explain your problem:

The .NET Framework Data Provider for SQL Server does not persist or return 
the password in a connection string unless you set Persist Security Info to true.

False is the default.

http://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqlconnection.connectionstring(v=vs.100).aspx

Upvotes: 2

Paul
Paul

Reputation: 3954

When comparing strings, it's better to use String1.Equals(String2). This will compare the values of the strings.

Upvotes: -1

Related Questions