Relative path to DB in connection string

♀尐吖头ヾ 提交于 2019-12-12 04:35:13

问题


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:


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)



来源:https://stackoverflow.com/questions/18911088/relative-path-to-db-in-connection-string

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!