2

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...

4

4 Answers 4

17

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();
Sign up to request clarification or add additional context in comments.

Comments

4

You should definitely use the ConnectionStringBuilder in this specific case as @M.A. 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.

1 Comment

If escaped it would have quotes around it.
2

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

1 Comment

And reassemble with String.Join.
2

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

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.