Last active
October 11, 2019 23:38
-
-
Save JimHume/467befb5d9380bebb7caede20b0dfbf1 to your computer and use it in GitHub Desktop.
Get the full path to a SQL CE database file
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public static class DbContextExtensions | |
{ | |
/// <summary> | |
/// Resolve the connection string for the given <see cref="DbContext"/>. This resolves variables in the | |
/// connection string to their local values. E.g. "Data Source=|DataDirectory|\Database.sdf" will resolve | |
/// to "C:\ProgramData\MyApp\Database.sdf". | |
/// </summary> | |
/// <param name="dbContext"><see cref="DbContext"/></param> | |
/// <returns><see cref="string"/>: The fully-resolved connection string.</returns> | |
public static string GetResolvedConnectionString(this DbContext dbContext) | |
{ | |
return GetResolvedConnectionString(dbContext.Database.Connection.ConnectionString); | |
} | |
/// <summary> | |
/// Resolve the given connection string by expanding variables and populating them with the appropriate | |
/// corresponding property values. E.g. "Data Source=|DataDirectory|\Database.sdf" will resolve | |
/// to "C:\ProgramData\MyApp\Database.sdf". | |
/// </summary> | |
/// <param name="connectionString"><see cref="string"/>: A connection string, typically originating from a | |
/// <see cref="DbContext"/>.</param> | |
/// <returns><see cref="string"/>: The fully-resolved connection string.</returns> | |
public static string GetResolvedConnectionString(string connectionString) | |
{ | |
using var sqlCeReplication = new SqlCeReplication {SubscriberConnectionString = connectionString}; | |
var subscriberConnectionString = sqlCeReplication.SubscriberConnectionString; | |
return new SqlCeConnectionStringBuilder(subscriberConnectionString).DataSource; | |
} | |
} | |
// As inspired by http://erikej.blogspot.com/2013/02/sql-server-compact-code-snippet-of-week_19.html |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment