user43051
user43051

Reputation: 345

Relative path to DB in connection string

I am developing a db application in C# and my current connection string is

@"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=D:\Shop.accdb;Persist Security Info=False;"

How can I modify it so that the db is in the folder of the project and not in D? I mean I am planning to send the project to a friend so I don't want to include the full path but just the folder of the project.

Thank you in advance!

Upvotes: 0

Views: 4101

Answers (1)

Steve
Steve

Reputation: 216343

Change your connection string to

 @"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=|DataDirectory|\Shop.accdb;" + 
  "Persist Security Info=False;";

|DataDirectory| is a substitution string that (for WinForms apps) will be set by the Framework to the value of the current directory.
In code (before any Data Access) it could be changed to something to your likes with

 AppDomain.CurrentDomain.SetData("DataDirectory", @"D:\temp");

See this thread on MSDN

However, keep in mind, that, if your reason to change that value arises for permissions problems, you would have the same problems storing your database in the same folder with your program (C:\program files) because that folder is also severely write restricted. The best way is to store your database in a subfolder of C:\PROGRAMDATA\<myAppDatabaseFolder>

string myFolder = Environment.GetFolderPath(Environment.SpecialFolder.CommonApplicationData);
myFolder = Path.Combine(myFolder, "myAppDatabaseFolder);
AppDomain.CurrentDomain.SetData("DataDirectory", myFolder);

(I suppose that your setup procedure creates the MyAppDatabaseFolder so I have no check for folder existance)

Upvotes: 3

Related Questions