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

给你一囗甜甜゛ 提交于 2021-01-29 21:22:41

问题


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");

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).

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).

thanks you!


回答1:


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 : 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"));

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



来源:https://stackoverflow.com/questions/22472713/using-a-relative-path-for-a-database-file-in-c-visual-studio-2013

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!