简体   繁体   中英

C# - Get file path from connection string

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 to check if the file exists at initialization and back it up if the file has been modified.

Sample connection string:

strConn = "Data Source=|DataDirectory|\dbAlias.sdf";

您可以使用SqlCeConnectionStringBuilder类来解析现有的Sql Compact连接字符串。

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())

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;
}

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());
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM