C# - Get file path from connection string

ε祈祈猫儿з 提交于 2020-01-21 07:36:22

问题


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

回答1:


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



回答2:


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




回答3:


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



回答4:


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


来源:https://stackoverflow.com/questions/6941943/c-sharp-get-file-path-from-connection-string

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!