1

I have this connection string :

OleDbConnection con = new OleDbConnection(@"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=..\Release\DB.accdb"); // Database Connection

I want my program to connect to the database without the "..\Release\" in the string. What I mean is, that i want the program to look for the database in the program's folder, without specifying the folder's name (whatever the folder's name is). How is that done?

4

2 回答 2

2

您应该将您的数据库添加到项目中(添加 -> 现有项目...)并设置Build ActionContent和:Copy to Output DirectoryCopy always

在此处输入图像描述

之后,您可以使用以下连接字符串:

 string cs = @"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=test.mdb;Persist Security Info=False;";

以下代码,将在程序文件夹或子文件夹中找到数据库文件:

string programPath = System.IO.Directory.GetParent(System.Reflection.Assembly.GetExecutingAssembly().Location).FullName;
var dbPath = System.IO.Directory.GetFiles(programPath, "*.accdb", SearchOption.AllDirectories).FirstOrDefault();
string cs = null;
if (!string.IsNullOrEmpty(dbPath))
{
    cs = string.Format("Provider=Microsoft.ACE.OLEDB.12.0;Data Source={0};Persist Security Info=False;", dbPath);
}
于 2013-10-27T15:47:37.007 回答
1

也许你可以使用类似的东西

String strAppDir = System.IO.Path.GetDirectoryName(
        System.Reflection.Assembly.GetExecutingAssembly().GetName().CodeBase);
String strFullPathToMyFile = System.IO.Path.Combine(strAppDir, "DB.accdb");

参考:

如何:获取应用程序目录

于 2013-10-27T15:46:41.220 回答