Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Embed MS Access Database in C# WinForm app

I have a C# winform application that accesses data from an MS Access database. This means my applications requires at least 2 files, the .exe file and the .accdb file. Is it possible to include the database in the .exe file, so my solution consists of a single file (the same way you would include an image in the project resources)? If it is possible, are they any major reasons why it shouldn't be done and how would you access the data from code? The project is a only a little one for personal use so if performance is hit it doesn't matter too much.

thanks in advance

like image 602
lace.john Avatar asked Nov 05 '10 14:11

lace.john


2 Answers

It can be done. Simply add it to your project as you would add any other file (right click project -> Add -> Existing Item), then cancel all the dialogs that will popup offering you to handle it for you, then right click your database from your project explorer, go to properties and select Build Action: Embedded Resource.

Then use the method below to dump your database into a temporary file, which you can create by calling Path.GetTempFileName.

internal void CreateBlankDatabase(string destFile)
{
    using (Stream source = new MemoryStream(Properties.Resources.MyEmbeddedDatabase))
    using (Stream target = File.Open(destFile, FileMode.Truncate))
    {
        source.CopyTo(target);
    }
}

(Note that MyEmbeddedDatabase would be your embedded database name). Then use your temporary file name in your connection string. Make sure you delete your temporary file after you're done. Also, as other said, you won't be able to modify and save any data.

like image 169
Juan Avatar answered Sep 18 '22 22:09

Juan


No it shouldn't be done. How would you send someone and update to the .exe file without them losing their data? Keep it separate.

You need to have a way to manage how your applications installs and the file location in your connection string(s). There could be a \Data subfolder in your app folder with the .accdb file(s) in it.

like image 35
JeffO Avatar answered Sep 18 '22 22:09

JeffO