4

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

4 Answers 4

6

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

Sign up to request clarification or add additional context in comments.

4 Comments

It would be nice to explain to him what property contains the DataDirectory he is looking for.
SqlCeConnectionStringBuilder.DataSource gives "|DataDirectory|\\dbPerson.sdf" again, not physical path.
@Nix: AppDomain.CurrentDomain.SetData("DataDirectory",path);
For LocalDB, use: new SqlConnectionStringBuilder(str).AttachDBFilename.Replace("|DataDirectory|", AppDomain.CurrentDomain.GetData("DataDirectory").ToString())
5

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

Comments

4

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 Comments

+1 because you give him the property that defines the directory.
I still need to find |DataDirectory| alias. Currently I know it but how about other aliases -if any- Absolute path would be nice....
Is there any other alias like |DataDirectory| ?
Does not work with LocalDB connectionstrings, it just returns "(LocalDB)\v11.0" on the DataSource property.
0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.