|DataDirectory| not obtained from configuration settings; you mix three different things:
ConfigurationManager.AppSettings["DataDirectory"]
This comes from the configuration settings; a .config file that you must create and place in your project. This particular setting is the value of the item with the "DataDirectory" key in the AppSettings item. This does not exist unless you put it in a .config file. Typically, here you put configuration or startup data that never changes. Here you should not indicate the paths to files, as they may be different on the computer where users install your database.
Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData)
This is the path to the current application data folder for the user, determined by the operating system on which the application is installed. You cannot change this; it is determined by the OS. You can be sure that this folder is writable by the user and will be available if the user switches to another computer or logs in. This is usually the place where you want to put editable user data.
SqlConnection("Data Source=|DataDirectory|DatabaseFileName.sdf;...")
This is the connection string for the ADO.NET connection. ADO.NET handles vertical columns on purpose; it looks for AppDomain data matching the key name between the vertical bars. You can get the same data with:
AppDomain.CurrentDomain.GetData("DataDirectory")
So what does the value of DataDirectory ? This is done regardless of the deployment of the executable:
- . MSI installers define it as the application’s destination folder.
- ClickOnce defines a special data folder in your project.
- Web applications use the App_Data folder.
- The Visual Studio debugger uses the debug folder.
Note that .MSI installers may allow the user to modify the DataDirectory; therefore, you should never hardcode or modify the DataDirectory , if you do this, to find where the application data has been deployed, there is no way. Usually you use the DataDirectory folder for read-only binary data deployed with your executable.
If you need to write data deployed along with your executable file, you must first copy it where you know that the user can write, for example, Environment.SpecialFolder.ApplicationData , and write to a copy. Not only is DataDirectory not necessarily written by users, it is part of the deployment, not part of user data; if you restore or delete the executable, DataDirectory will be reinstalled or deleted. Users do not like it when you delete their data, so do not save it to a DataDirectory .