简体   繁体   中英

How to replace part of Connection String?

I'm using c# and I need to replace a string with other data. This is the string, the servername, user1 and 380kj data and length can change.

"Data Source=servername;User ID=user1;Password=380kj"

I want this result:

"Data Source=servername;User ID=XXXXX;Password=XXXXX"

I have done an IndexOf on User ID and Password but I don't know how to get the exact count to use the remove function so I can then insert the XXXXX into the string.

   int index = SaleDatabase.ConnectionString.IndexOf("User ID=");
   int index2 = SaleDatabase.ConnectionString.IndexOf(";Password");

What can I do?

thanks...

You can use the String.Replace method, but it seems that in your case you are editing a database connection string, in which case you should use the specific ConnectionStringBuilder for that connection string, such as:

string connStr = "Data Source=servername;User ID=user1;Password=380kj";
System.Data.SqlClient.SqlConnectionStringBuilder sb = new System.Data.SqlClient.SqlConnectionStringBuilder(connStr);
sb.UserID = "XXXXX";
sb.Password = "XXXXX";
connStr = sb.ToString();

Why not split the string by using Split Method by character (";"). Result will be array. Then u can fetch value from result array using simple linq or foreach loop

You should definitely use the ConnectionStringBuilder in this specific case as @MA Hamm suggested. But for completeness, you can also do something like this with a simple Regex.Replace . Something like:

    Regex r = new Regex(@"User ID=[^;]*");
    String newString = r.Replace(s,"User ID=XXXX");

Will look for text starting with User ID= and capture all characters up to the next ; (note: if user id contains a ; this would break - but it probably would have broken anyway and would need to have been escaped). Then we just replace the matched string with our new string.

Doing the same for Password= is left as an exercise for the reader.

Just use string.Format and generate a new string , for sample:

public static string GenerateConnectionString(string dataSource, string user, string password)
{
   return string.Format("Data Source={0};User ID={1};Password={2}", dataSource, user, password);
}

Some solutions can be very simple. Read more about KISS

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM