Skip to content Skip to sidebar Skip to footer

How To Correctly Move Location Of .mdf File And Change Connection String's Datadirectory Accordingly

Currently my SQL database is on C:\Users\Slaven\KasaMP.mdf I want to move it into my projects directory [maybe 'database' folder(?)] and make correct changes on my connectionstri

Solution 1:

In a WinForms application the DataDirectory substitution string point to the folder where the application starts. In case of a Visual Studio session this folder is the BIN\DEBUG or BIN\RELEASE folder (possibly with the x86 variant)

This works well inside Visual Studio but you should be aware that, in your customer PC and without changing the config setting, the folder where you should have the MDF is the same of your app. But, sadly this location has no write permissions (like C:\program files). An essential requirement for any database app.

So your best bet is to place this file in the CommonApplicationData folder that you can retrieve using Environment.SpecialFolder.CommonApplicationData enum (usually it is C:\PROGRAMDATA in latest version of Windows)

string folder = Environment.GetFolderPath(Environment.SpecialFolder.CommonApplicationData);
string myAppFolder = Path.Combine(folder, "MyReservedAppDataFolder");
Directory.CreateDirectory(myAppFolder);
AppDomain.CurrentDomain.SetData("DataDirectory", myAppFolder);

All this should be done BEFORE any data access related code in your application. Of course you can leave the setting as it is now without making any change.

Post a Comment for "How To Correctly Move Location Of .mdf File And Change Connection String's Datadirectory Accordingly"