查找并删除部分字符串,然后使用新值

时间:2016-12-13 13:26:08

标签: c# .net linq

下面是我在很多地方使用的连接字符串。

<add key="conString" value="Data Source=My-Pc;Initial Catalog=Db1;User ID=sdfsdf;Password=facebook"></add>

现在我首先要从连接字符串中删除 initialcatalog 部分以及数据库,稍后我想添加 initialcatalog 部分和新的数据库名称。

以下是代码:

public void statistics()
{
   String connString = System.Configuration.ConfigurationManager.AppSettings["conString"];
   //here i want to remove this part :  Initial Catalog=Db1;
   connString = "Data Source=My-Pc;User ID=sdfsdf;Password=facebook";

   //Here I have lots of operation and after that I would like to add this part with new database name

   string newDb= "db2";
   //again add that part with new db :  Initial Catalog=Db2;
   connString = "Data Source=My-Pc;Initial Catalog=Db2;User ID=sdfsdf;Password=facebook";
}

1 个答案:

答案 0 :(得分:1)

// initialize ConnectionStringBuilder like so:
String connString = System.Configuration.ConfigurationManager.AppSettings["conString"];

var builder = new ConnectionStringBuilder(connString);
// set initial catalog to other database: 
builder.InitialCatalog = "<otherDatabaseName>";
// retrieve new connectionstring
var newConnectionString = builder.ToString();