0

I have been using a LocalDB.mdf file to build my application, but now need to use it in production and create an installable application.

After research, it seems the best place to store such a file is in the /Appdata/Local/ folder.

I intend to create a new LocalDB.mdf file in there if it doesnt already exist, or has been deleted.

I have a pre-made LocalDB.mdf file in my App Resources, which I wanted to copy into this /Appdata/Local/ folder on first run, but I am seeing an Access is denied error.

I can create a blank file ok to that folder.

Here is the code:

string appDataFolder = Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData);
        string dvAppDataFolder = appDataFolder + @"\MyApp";
        AppDomain.CurrentDomain.SetData("DataDirectory", dvAppDataFolder);

        if (!Directory.Exists(dvAppDataFolder))
            Directory.CreateDirectory(dvAppDataFolder);

        if (!File.Exists(dvAppDataFolder + "LocalDB.mdf"))
        {
            File.WriteAllBytes(dvAppDataFolder, LokiServer.Properties.Resources.newDB);
        }

In addition, Am I going about this the right way?

leppie
  • 115,091
  • 17
  • 196
  • 297
Dan Sewell
  • 1,278
  • 4
  • 18
  • 45

1 Answers1

2

This line

if (!File.Exists(dvAppDataFolder + "LocalDB.mdf")) 

is probably wrong. Missing the backslash, better to use Path.Combine instead of a string concatenation.

Finally, you want to write to a file not to a folder

 string fileName = Path.Combine(dvAppDataFolder,"LocalDB.mdf");
 if (!File.Exists(fileName))
 {
        File.WriteAllBytes(fileName, LokiServer.Properties.Resources.newDB);
 }

Are you doing it right? It depends. If your app data should be kept separated for each user of your target machine then you are right, but if you want your database to be available to all users of that machine then use

string appDataFolder = Environment.GetFolderPath
                      (Environment.SpecialFolder.CommonApplicationData);
Steve
  • 213,761
  • 22
  • 232
  • 286