2

I have a string that contains a login, database, and a password.

string str = "user Id=abc, database=DDD, Password=mypasswd"  

I want to be able to replace the database value "DDD" with a different value.

I tried using the string.Replace, but I won't know what the existing database will be.

Does anyone know of a simple solution?

4
  • 2
    Split the string at commas. Split each resulting string at equal signs. Replace the second value where the first value is "database". Join back. Commented Apr 24, 2013 at 17:48
  • 1
    Is it just for connection string? In that case you can use ConnectionStringBuilder , which parses and initializes different properties, and you can easily change database property and get back new string with new value. Commented Apr 24, 2013 at 17:50
  • I'm not to familiar with the ConnectionStringBuilder. I'll look into it. Thank you. Commented Apr 24, 2013 at 18:00
  • @hmakled, I have added the answer and I also posted link to MSDN which says that this is the the only safe way. Commented Apr 24, 2013 at 18:02

7 Answers 7

11

Following is the only recommended way by MSDN to prevent Connection String Injection Attacks

http://msdn.microsoft.com/en-us/library/ms254947.aspx

// cs stores previous connection string which came from config

System.Data.SqlClient.SqlConnectionStringBuilder builder = 
    new System.Data.SqlClient.SqlConnectionStringBuilder(cs);
builder.InitialCatalog = "NEWDB";

// you get your database name replaced properly...
cs = builder.ToString();

Based on the type of database or database driver, you have to use different class, for MySql it should be MySqlConnectionStringBuilder and name of property might be Database.

Sign up to request clarification or add additional context in comments.

10 Comments

This is the whole reason ConnectionStringBuilder was created.
Yeah, and one other nice thing is that it's capable of splitting up more complex connection strings that contain uncommon attributes as well.
I can't access/find SqlConnectionStringBuilder am I missing a class for it?
Include namespace System.Data.SqlClient
@AkashKava I added the namespace but still can't access SqlConnectionStringBuilder??
|
5

One alternative is to use a Regex, this would do the replace for you:

using System.Text.RegularExpressions;

string cStr = "user Id=abc, database=DDD, Password=mypasswd";
Console.WriteLine(cStr);

Regex r = new Regex("(?<=database=)(.+?)(?=,)");
cStr = r.Replace(cStr, "NewDatabaseName");

Console.WriteLine(cStr);

NOTE: this was compiled, run, and proven with scriptcs so it's fairly droppable into your solution.

8 Comments

what class does Regex use? I can't seem to access it.
@hmakled, the class name in Regex, msdn.microsoft.com/en-us/library/…
@hmakled, add a using System.Text.RegularExpressions; at the top of your .cs file.
Ok did that and it shows now, but where is my string in the example you showed?
@hmakled, in the example you showed you used a variable named str, note that I'm reassigning str and using it in the Replace method call.
|
4

How about using String.Format?

string username = "abc";
string database = "myDB";
string password = "my_pw";

string str = String.Format("user Id={0}, database={1}, Password={2}",
                           username, database, password);

You could then load these values (or even the whole connection string) from a configuration file.

3 Comments

the string is already existing and its longer than i displayed. I'm not creating the string i'm pulling it from a configuration file.
Ah, yea that makes a big difference. Unless you don't have an appropriate answer already, I'll put one together once I get home.
@eandersson, I did it before you get home :)
2

Regexes are also an option:

string str = "user Id=abc, database=DDD, Password=mypasswd",
    newDatabase = "newDb";

Console.WriteLine( Regex.Replace( str, @"(?<=database=)(.*?)(?=,)", m => newDatabase ) );

3 Comments

@MichaelPerrenoud yes, I was surprised no one posted it. So +1 to you as well for solidarity :D
@BlackBear - tried your way but its not replacing the value. stays the same
@hmakled regex.replace returns the new string and leaves the input one untouched
1

Split the string at the comma separator, then take the second index of the resulting array, split at the equal separator, substitute the second element, then recombine all

string str = "user Id=abc, database=DDD, Password=mypasswd";
string[] parts = str.Split(',');
string[] dbparts = parts[1].Split('=');
dbparts[1] = "new_database_name";

parts[1] = string.Join("=", dbparts);
string final = string.Join(", ", parts);

and, well, with a bit of error checking would be safer.

Comments

0

Same as above but if you are fun of LINQ

string str = "user Id=abc, database=DDD, Password=mypasswd";

var q = from part in str.Split(new[] {','})
                let trimedPart= part.Trim()
                let replacedPart  =trimedPart.StartsWith("database=")?trimedPart.Replace("DDD","newValue"):trimedPart
                select replacedPart;

        var newConStr = q.Aggregate((current, next) => current + "," + next);

Comments

0

These solutions are all great, but doesn't one long and confusing line have a certain elegance?

"user Id=abc, database=DDD, Password=mypasswd".Substring(0, "user Id=abc, database=DDD, Password=mypasswd".IndexOf("database=")) + "database=" + "[YOUR VALUE HERE]" + ", " + "user Id=abc, database=DDD, Password=mypasswd".Substring("user Id=abc, database=DDD, Password=mypasswd".IndexOf("Password="))

Output: user Id=abc, database=[YOUR VALUE HERE], Password=mypasswd

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.