Is there any connection string parser in C#?

后端 未结 9 892
遥遥无期
遥遥无期 2020-11-28 05:09

I have a connection string and I want to be able to peek out for example \"Data Source\". Is there a parser, or do I have to search the string?

9条回答
  •  -上瘾入骨i
    2020-11-28 05:48

    You can use DbConnectionStringBuilder, and you don't need any specific provider:

    The following code:

    var cnstr = "Data Source=data source value;Server=ServerValue";
    var builder = new DbConnectionStringBuilder();
    builder.ConnectionString = cnstr;
    Console.WriteLine("Data Source: {0}", builder["Data Source"]);
    Console.WriteLine("Server: {0}", builder["Server"]);
    

    Outputs to console:

    Data Source: data source value
    Server: ServerValue
    

    EDIT:

    Since DbConnectionStringBuilder implements IDictionary you can enumerate the connection string parameters:

    foreach (KeyValuePair kv in builder)
    {
        Console.WriteLine("{0}: {1}", kv.Key, kv.Value);
    }
    

提交回复
热议问题