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!

Guru Stron
  • 102,774
  • 10
  • 95
  • 132
user43051
  • 345
  • 2
  • 5
  • 17

1 Answers1

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)

Steve
  • 213,761
  • 22
  • 232
  • 286
  • hi it worked for me, i specified AppDomain.CurrentDomain.SetData("DataDirectory", Application.StartupPath); under constructor method of each class – Pranesh Janarthanan Apr 04 '16 at 07:32