Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# - Replacing characters in a string

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?

like image 529
hmakled Avatar asked Jul 23 '26 06:07

hmakled


1 Answers

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.

like image 66
Akash Kava Avatar answered Jul 25 '26 21:07

Akash Kava