Reputation: 46651
How can I change part of a ConnectionString
with LINQ to XML
. For example, I only want to change the Data Source
and Initial Catalog
values in the following:
<connectionStrings>
<add name="connStr" connectionString="Data Source=data-source;Initial Catalog=db;User ID=user;Password=pass" providerName="System.Data.SqlClient;MultipleActiveResultSets=true;" />
</connectionStrings>
I understand how to change the whole connectionString attribute, but I don't want to do that, I only want to change certain parts.
I am using the following code to modify parts of a connection string and for the most part it works, but I how can I modify it so it does not remove the attribute/values that are not separated by ;
, providerName
in this case.
string[] connArr = connectionString.Value.Split(';');
for (int i = 0; i < connArr.Length; i++)
{
//Get the attribute and the value splitted by the "="
string[] arrSubConn = connArr[i].Split('=');
if (arrSubConn.Length == 2)
{
string connAttr = arrSubConn[0];
string connVal = arrSubConn[1];
//Change the server name
if (connAttr == "Data Source")
connVal = environmentSettings.Server;
//Change the database name
if (connAttr == "Initial Catalog")
connVal = environmentSettings.Database;
newConnString += String.Format("{0}={1};", connAttr, connVal);
}
}
Upvotes: 0
Views: 214
Reputation: 25224
LINQ to XML will only be able to recover the actual connectionString attribute for you. Manipulation of the actual string element is beyond LINQ to XML's capabilities. If you want to change the string itself you are going to need to manipulate it with other functions. A quick way to do that might be to split the string on = and ;. You know that every element with an even index is a key and every odd index element is a value. You can then search for the Data Source and Initial Catalog elements and modify the values in the next array locations.
Upvotes: 1
Reputation: 14682
Please refer to the documentation:
http://msdn.microsoft.com/en-us/library/bb387061.aspx
Upvotes: 1