非常简单的问题:
我想将连接字符串拆分为其关键字/值对,例如以下连接字符串:
Provider=SQLOLEDB.1;Integrated Security=SSPI;Persist Security Info=False;Initial Catalog=vm-jp-dev2;Data Source=scsql\sql2005;Auto Translate=False
会变成:
Provider=SQLOLEDB.1
Integrated Security=SSPI
Persist Security Info=False
Initial Catalog=vm-jp-dev2
Data Source=scsql\sql2005
Auto Translate=False
问题是MSDN documentation表明如果值包含在单引号或双引号字符中,则允许连接字符串值包含分号(如果我理解,则以下内容有效):
Provider="Some;Provider";Initial Catalog='Some;Catalog';...
分割此字符串的最佳方式是什么(在C#中)?
答案 0 :(得分:9)
有一个DBConnectionStringBuilder类可以做你想要的......
System.Data.Common.DbConnectionStringBuilder builder = new System.Data.Common.DbConnectionStringBuilder();
builder.ConnectionString = "Provider=\"Some;Provider\";Initial Catalog='Some;Catalog';";
foreach (string key in builder.Keys)
{
Response.Write(String.Format("{0}: {1}<br>", key , builder[key]));
}
答案 1 :(得分:0)
您应该实现某种简单的字符串解析重新引用。这样的事情:
public static IEnumerable<string> SplitString(string str)
{
int StartIndex = 0;
bool IsQuoted = false;
for (int I = 0; I < str.Length; I++)
{
if (str[I] == '"')
IsQuoted = !IsQuoted;
if ((str[I] == ';') && !IsQuoted)
{
yield return str.Substring(StartIndex, I - StartIndex);
StartIndex = I + 1;
}
}
if (StartIndex < str.Length)
yield return str.Substring(StartIndex);
}
答案 2 :(得分:0)
你可以写一个迷你解析器。移动字符串以跟踪引用状态。一般来说可能更可靠。
另一种选择是使用正则表达式,并匹配整个内容,可以在regex.Split
中捕获而不是跳过输出:
var re = new Regex(@"([\w\s]+=\s*?(?:['""][\w\s]+['""]|[\w\s]+));");
var parts = re.Split(connectionString)
这假定:
就个人而言,如果我不能很快地训练正则表达式,我会选择解析器。
编辑:有一种更简单的方法。 DbConnectionStringBuilder
实现了IEnumerable
,所以让它去完成工作:
using System;
using System.Collections.Generic;
using System.Data.Common;
class Program {
static void Main(string[] args) {
string conStr = @"Provider=SQLOLEDB.1;Integrated Security=SSPI;Persist Security Info=False;Initial Catalog=vm-jp-dev2;Data Source='scsql\sql;2005';Auto Translate=False";
var cb = new DbConnectionStringBuilder();
cb.ConnectionString = conStr;
int n = 0;
foreach (KeyValuePair<string, object> c in cb) {
Console.WriteLine("#{0}: {1}={2}", ++n, c.Key, c.Value);
}
}
}
答案 3 :(得分:0)
如果是SQL Server,您只需执行以下操作:
SqlConnectionStringBuilder decoder = new SqlConnectionStringBuilder(connectionString);
string UserID = decoder.UserID;
string Password = decoder.Password;
等