C# - Get file path from connection string

后端 未结 4 1791
隐瞒了意图╮
隐瞒了意图╮ 2021-01-13 22:10

Is there an existing method in C# to extract the file path from a string that represents a ConnectionString to a SqlCE .sdf file? I want t

相关标签:
4条回答
  • 2021-01-13 22:21

    You could just create the connection and get the data source from it as a property:

    string data;
    using (var conn = new SqlConnection(connectionString)) {
        data = conn.DataSource;
    }
    
    0 讨论(0)
  • 2021-01-13 22:27

    You can use SqlCeConnectionStringBuilder class to parse existing Sql Compact connection string.

    0 讨论(0)
  • 2021-01-13 22:30

    A bit late perhaps, but I came across this question wile struggling with the same problem. You can find the location of the |DataDirectory| folder with AppDomain.CurrentDomain.GetData("DataDirectory"). So your connectionstring can be translated like this:

    strConn .Replace("|DataDirectory|", AppDomain.CurrentDomain.GetData("DataDirectory").ToString())
    
    0 讨论(0)
  • 2021-01-13 22:40

    For LocalDB and SqlConnection (not CE):

    public static string GetFilePathFromConnectionString(string connectionString)
    {
        var attachDbFileName = new SqlConnectionStringBuilder(connectionString).AttachDBFilename;
        return attachDbFileName.Replace("|DataDirectory|", AppDomain.CurrentDomain.GetData("DataDirectory").ToString());
    }
    
    0 讨论(0)
提交回复
热议问题