【问题标题】:Opening Access Database with C#使用 C# 打开 Access 数据库
【发布时间】:2023-03-17 09:06:01
【问题描述】:

我有这个连接字符串:

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

我希望我的程序在字符串中没有“..\Release\”的情况下连接到数据库。 我的意思是,我希望程序在程序文件夹中查找数据库,而不指定文件夹的名称(无论文件夹的名称是什么)。 这是怎么做到的?

【问题讨论】:

  • 你试过只删除`\Release`吗?
  • 我试过 .. 我得到这个错误:'E:\Dangerous\Programming\C# Projects\My Projects\Incompleted Projects\ExaminerApp\ExaminerApp\bin\Debug\...\DB.accdb'不是有效路径。确保路径名拼写正确,并且您已连接到文件所在的服务器。
  • 好吧..这很正确,因为您的 Debug 文件夹中没有 .accdb 文件.. 在那里对接数据库。经验法则是:如果您不指定路径,程序将在与.exe 文件相同的文件夹中查找。

标签: c# winforms ms-access


【解决方案1】:

您应该将您的数据库添加到项目中(添加 -> 现有项目...)并将 Build Action 设置为 Content 并将 Copy to Output Directory 设置为 Copy 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);
}

【讨论】:

  • @John,不客气。我添加了代码以在子文件夹中查找 db 文件。
【解决方案2】:

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

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

参考:

How to: Get the Application Directory

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多