简体   繁体   English

在c#,visual studio 2013中使用数据库文件的相对路径

[英]Using a relative path for a database file in c#, visual studio 2013

inside my code i am using this command: 在我的代码里面我使用这个命令:

conn = new OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0; Data Source =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”);

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”(里面有解决方案文件及其所有目录和数据库文件)。

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). 所以我想使用一个相对路径来调用位于maxstar01内的database.accdb(之前没有所有路径)。

thanks you! 谢谢!

You can use AppDomain.CurrentDomain.BaseDirectory to get the application directory. 您可以使用AppDomain.CurrentDomain.BaseDirectory来获取应用程序目录。

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

Edit : When developing a Windows/Console app, AppDomain.CurrentDomain.BaseDirectory may point to the "\\bin\\debug" directory instead of the root. 编辑 :在开发Windows /控制台应用程序时, AppDomain.CurrentDomain.BaseDirectory可能指向“\\ bin \\ debug”目录而不是根目录。 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"));

If you'd like to write code that works with both Web and Windows applications, you could take a look at this answer . 如果您想编写适用于Web和Windows应用程序的代码,您可以查看此答案

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM