0

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!

1 Answer 1

3

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)

Sign up to request clarification or add additional context in comments.

1 Comment

hi it worked for me, i specified AppDomain.CurrentDomain.SetData("DataDirectory", Application.StartupPath); under constructor method of each class

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.