I have a Winforms application that uses a SQL Server Compact .SDF
database to store data. The application runs fine in Visual Studio when debugging, though when I use the "Publish" option of my project and run the program after installation, I always get an error saying "The database file cannot be found".
I set the connection string as follows
string fileName = System.IO.Path.Combine(System.Windows.Forms.Application.StartupPath, "Cellar.sdf");
connString = string.Format("Data Source={0};", fileName);
The database Cellar.sdf
is inside my program folder.
It is obvious that the path to the database is wrong, but is there a way for me to set the path where I want my application to be installed when using the "Publish" function, or some way to find out where the database file gets copied? What is the proper approach to include a local database file in a desktop application?
You can include the DataDirectory macro, and set the location to an suitable place in code.
connString = string.Format("Data Source=|DataDirectory|\{0};", fileName);
private void Application_Startup(object sender, StartupEventArgs e)
{
// This is our connection string: Data Source=|DataDirectory|\Chinook40.sdf
// Set the data directory to the users %AppData% folder
// So the Chinook40.sdf file must be placed in: C:\\Users\\<Username>\\AppData\\Roaming\\
AppDomain.CurrentDomain.SetData("DataDirectory", Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData));
}
This will require you to copy the database file to the desird location (if it does not exist already) during initial application launch.