连接字符串中的DB的相对路径 [英] Relative path to DB in connection string
问题描述
我在C#中开发一个数据库应用程序,我当前的连接字符串是
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;
如何修改它,在项目的文件夹而不是在D?我的意思是,我打算把项目发送给朋友,所以我不想包括完整的路径,而只是项目的文件夹。
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.
提前谢谢
推荐答案
将连接字符串更改为
@"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=|DataDirectory|\Shop.accdb;" +
"Persist Security Info=False;";
| DataDirectory |
(对于WinForms应用程序)将由框架设置为当前目录的值。
在代码中(在任何数据访问之前),它可以更改为喜欢与
|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");
但是,请记住,如果您的原因更改该值出现权限问题,您会有同样的问题将您的数据库存储在同一个文件夹与您的程序(C:\program文件),因为该文件夹也是严重写限制。最好的方法是将数据库存储在 C:\PROGRAMDATA\< myAppDatabaseFolder>
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);
(我想你的安装过程创建 MyAppDatabaseFolder
,所以我没有检查文件夹存在)
(I suppose that your setup procedure creates the MyAppDatabaseFolder
so I have no check for folder existance)
这篇关于连接字符串中的DB的相对路径的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!