Tutorial :string.Format and the word “Password”



Question:

Using C#, I need to build a connection string from a few AppSettings. If I do this:

Connection = string.Format("Data Source={0};Initial Catalog={1);User Id={2};Password={3};",    ConfigurationManager.AppSettings.Get("CartServer"),    ConfigurationManager.AppSettings.Get("CartDatabase"),    ConfigurationManager.AppSettings.Get("CartUserName"),    ConfigurationManager.AppSettings.Get("CartPassword"));  

I get an invalid format string exception. I narrowed it down to the "Password=" part of the format string (ie, "Passwork=" works). There's an easy enough work-around:

Connection = string.Format("Data Source={0};Initial Catalog={1);User Id={2};{3}={4};",    ConfigurationManager.AppSettings.Get("CartServer"),    ConfigurationManager.AppSettings.Get("CartDatabase"),    ConfigurationManager.AppSettings.Get("CartUserName"),    "Password",ConfigurationManager.AppSettings.Get("CartPassword")); // Lame!!!  

But what's the real story with the "Password"? I checked MSDN and a few other sites but came up empty. Oh, if it matters, this is a WCF service.


Solution:1

Your problem is the {1) in the format string; it should be {1} (you have closed the brace with a parenthesis)

This is causing your FormatException because your format string is now invalid. Why your second entry works is beyond me though.

Edit: I agree with the other Richard that you should consider using a connection string builder object.


Solution:2

Have you considered the DbConnectionStringBuilder class (or one of its subtypes)?


Solution:3

Obvious.... your problem is because this: "(".

Why don't you use StringBuider class, is easier :)


Solution:4

I just Google'd and I had no idea a "DbConnectionStringBuilder" even existed. Wow, you learn something new everyday.

Also, for other connection strings, check this site out: http://www.connectionstrings.com/


Solution:5

Why StringBuilder is better than string.Format?

Please check this Is String.Format as efficient as StringBuilder to see why...


Note:If u also have question or solution just comment us below or mail us on toontricks1994@gmail.com
Previous
Next Post »