Question

I have an n-tier application that uses a data access layer. In the data access layer project settings, there is a connection string. The string contains the text "Data Source=|%LOCALAPPDATA%|\Some Folder\File.ext" but when the application is run (and the file is there) I get an OleDbException "Not a valid File."

Am I writing the string wrong, or is this due to some other problem?

Also, if the user has Windows XP, will this directory point to anything? I'm making the installer, install an Access database to this particular folder, but I don't think XP has a "LocalAppData", but just "AppData".

Was it helpful?

Solution

You can get and replace the predefined environment variable with this code

string str = Environment.ExpandEnvironmentVariables("%LOCALAPPDATA%");
string expandedConString = "Data Source=|%LOCALAPPDATA%|\Some Folder\File.ext".Replace("|%LOCALAPPDATA%|", str);

By the way, the %LOCALAPPDATA% environment variable points at the same value of

string str = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData);

However I find this machinery is a bit clumsy. A better approach is to use the |DataDirectory| substitution string. You write your connection string with the standard

"Data Source=|DataDirectory|\Some Folder\File.ext"

then in your app, before any data access code you change the current value for |DataDirectory| reading a configuration settings and changing its value with

string myDBPath = ConfigurationManager.AppSettings["PathToDatabase"].ToString();
AppDomain.CurrentDomain.SetData("DataDirectory", myDBPath);

In this way your application will be more flexible and will adapt easily to different external constraints that your customers undoubtedly will pose.
(Of course your installer should choose or configure a directory where you have full read/write permission on your database file)

For completeness

Where is DataDirectory

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top