1

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.

enter image description here

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?

Kirk Broadhurst
  • 27,836
  • 16
  • 104
  • 169
Daniel B
  • 8,770
  • 5
  • 43
  • 76

1 Answers1

1

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.

ErikEJ
  • 40,951
  • 5
  • 75
  • 115
  • I can run a line of code to check if it already exists, or otherwise copy it there, though, how am I to copy it? I know the destination, but how can I figure out where it's being deployed on installation? If I could set that location right away, I wouldn't need to copy it. A lot of work when it should be possible to just select a location to place it in my opinion. – Daniel B Aug 28 '13 at 13:20
  • If you do not require the database to survive app updates, simply use DataDirectory with no code – ErikEJ Aug 28 '13 at 14:13
  • 1
    I ended up doing this, `string fileName = System.IO.Path.Combine(ApplicationDeployment.CurrentDeployment.DataDirectory, "Cellar.sdf"); Console.WriteLine(fileName); connString = string.Format("Data Source={0};", fileName);` Though I'd consider your solution as a more proper way to do it! – Daniel B Aug 28 '13 at 14:20