在 c# 中使用数据库文件的相对路径,visual studio 2013 [英] Using a relative path for a database file in c#, visual studio 2013

查看:48
本文介绍了在 c# 中使用数据库文件的相对路径,visual studio 2013的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的代码中,我使用了这个命令:

inside my code i am using this command:

conn = new OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0; 数据源 =C:\Users\ori\Documents\Visual Studio 2013\Projects\maxstar01\Database.accdb");

conn = new OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0; Data Source =C:\Users\ori\Documents\Visual Studio 2013\Projects\maxstar01\Database.accdb");

我在一个程序员团队中,我们都在自己的计算机上工作,但每个人都使用相同的文件夹名称maxstar01"(里面有解决方案文件及其所有目录和数据库文件).

i am in a team of programmers which we all work on our own computers but everyone are using the same folder name "maxstar01" (which inside there is the solution file and all of it's directories and that database file).

所以我想使用一个相对路径来调用位于 maxstar01 内的 database.accdb(没有之前的所有路径).

so i want to use a relative path which will call the database.accdb that sits inside the maxstar01 (without all of the path before that).

谢谢!

推荐答案

您可以使用 AppDomain.CurrentDomain.BaseDirectory 获取应用程序目录.

You can use AppDomain.CurrentDomain.BaseDirectory to get the application directory.

conn = new OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0; Data Source =" + Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Database.accdb"));

Edit :在开发 Windows/Console 应用程序时,AppDomain.CurrentDomain.BaseDirectory 可能指向\bin\debug"目录而不是根目录.在这种情况下,您可以使用 ..\..\ 向上移动两级并获取程序的根目录.

Edit : When developing a Windows/Console app, AppDomain.CurrentDomain.BaseDirectory may point to the "\bin\debug" directory instead of the root. In that case, you could use ..\..\ to move two levels up and obtain your program's root directory.

conn = new OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0; Data Source =" + Path.Combine(AppDomain.CurrentDomain.BaseDirectory, @"..\..\Database.accdb"));

如果您想编写适用于 Web 和 Windows 应用程序的代码,您可以查看此答案.

If you'd like to write code that works with both Web and Windows applications, you could take a look at this answer.

这篇关于在 c# 中使用数据库文件的相对路径,visual studio 2013的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆