2011-12-15 89 views
3

是否有一個標準庫或代碼片段來獲取帶有連接字符串的值?解析連接字符串

string connstr = "DataServiceUrl=http://localhost/foo;" + 
     "RemoteServerConnection={server=http://localhost/foo2;interface=0.0.0.0;};" + 
     "publisherport=1234;StatisticsURL=http://localhost/foo3"; 

整個內部連接屬性是一種把它扔在一個循環中。我想根據一個關鍵字獲得特定的值。

這裏是答案作者:John我用:

System.Data.Odbc.OdbcConnectionStringBuilder builder = new System.Data.Odbc.OdbcConnectionStringBuilder(); 
builder.ConnectionString = this.ConnectionString; 
MessageBox.Show(builder["RemoteServerConnection"]); 
+11

參見[連接字符串生成器( http://msdn.microsoft.com/en-us/library/ms254947.aspx) – 2011-12-15 18:13:58

回答

5

由(")更換 「{」 和 「}」 的伎倆:

string conn = "DataServiceUrl=http://localhost/foo;" + 
    "RemoteServerConnection={server=http://localhost/foo2;interface=0.0.0.0;};" + 
    "publisherport=1234;StatisticsURL=http://localhost/foo3"; 

var builder = new System.Data.Common.DbConnectionStringBuilder(); 
builder.ConnectionString = conn.Replace("{", "\"").Replace("}", "\""); 
var keys = builder.Keys; 
var values = builder.Values; 
string remoteServerConnection = (string)builder["RemoteServerConnection"];