C# 具有数据库文件相对路径的连接字符串
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1833640/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Connection string with relative path to the database file
提问by Martin
I load data from sdf database in winforms App. I use full path to the database file . Example :
我从 winforms App 中的 sdf 数据库加载数据。我使用数据库文件的完整路径。例子 :
conn = new SqlCeConnection
{
ConnectionString ="Data Source=F:\My Documents\Project1\bin\Debug\Database.sdf"
};
I d like use a relative path to the database file. For example. I have sdf file in folder F:\My Documents\Project1\bin\Debug\Data\file.sdf and I want use relative path in connection string. Any advice ? Thank you.
我想使用数据库文件的相对路径。例如。我在文件夹 F:\My Documents\Project1\bin\Debug\Data\file.sdf 中有 sdf 文件,我想在连接字符串中使用相对路径。有什么建议吗?谢谢你。
回答by RC1140
Relative to what, your application ? If so then you can simply get the applications current Path with :
相对于什么,您的应用程序?如果是这样,那么您可以简单地使用以下命令获取应用程序的当前路径:
System.Environment.CurrentDirectory
And append it to the connection string
并将其附加到连接字符串
回答by Nime Cloud
Relative path:
相对路径:
ConnectionString = "Data Source=|DataDirectory|\Database.sdf";
Modifying DataDirectory as executable's path:
将 DataDirectory 修改为可执行文件的路径:
string executable = System.Reflection.Assembly.GetExecutingAssembly().Location;
string path = (System.IO.Path.GetDirectoryName(executable));
AppDomain.CurrentDomain.SetData("DataDirectory", path);
回答by Elias Hossain
Would you please try with below code block, which is exactly what you're looking for:
你能不能试试下面的代码块,这正是你要找的:
SqlConnection conn = new SqlConnection
{
ConnectionString = "Data Source=" + System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().GetName().CodeBase) + "\Database.sdf"
};
回答by styler1972
This worked for me:
这对我有用:
string Connection = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source="
+ HttpContext.Current.Server.MapPath("\myPath\myFile.db")
+ ";Extended Properties=\"Excel 12.0 Xml;HDR=YES\"";
I'm querying an XLSX file so don't worry about any of the other stuff in the connection string but the Data Source.
我正在查询一个 XLSX 文件,所以不要担心连接字符串中的任何其他内容,但数据源。
So my answer is:
所以我的回答是:
HttpContext.Current.Server.MapPath("\myPath\myFile.db")
回答by Ck.Nitin
Try this code to the working directory if database file exists like below.
如果数据库文件存在如下所示,请将此代码尝试到工作目录。
D:\HMProject\DataBase\HMProject.sdf
D:\HMProject\DataBase\HMProject.sdf
string Path = Environment.CurrentDirectory;
string[] appPath = Path.Split(new string[] { "bin" }, StringSplitOptions.None);
AppDomain.CurrentDomain.SetData("DataDirectory", appPath[0]);
Connection string for .sdf file
.sdf 文件的连接字符串
<add name="LocalDB" connectionString="metadata=res://*/Client.HMProject.csdl|res://*/Client.HMProject.ssdl|res://*/Client.HMProject.msl;provider=System.Data.SqlServerCe.4.0;provider connection string="Data Source=|DataDirectory|\Database\HMProjectDB.sdf;Password=HMProject;Persist Security Info=False;"" providerName="System.Data.EntityClient" />
<add name="LocalDB" connectionString="metadata=res://*/Client.HMProject.csdl|res://*/Client.HMProject.ssdl|res://*/Client.HMProject.msl;provider=System.Data.SqlServerCe.4.0;provider connection string="Data Source=|DataDirectory|\Database\HMProjectDB.sdf;Password=HMProject;Persist Security Info=False;"" providerName="System.Data.EntityClient" />
Thanks
谢谢
ck.Nitin (TinTin)
ck.Nitin(丁丁)
回答by tomg
After several strange errors with relative paths in connectionstring I felt the need to post this here.
在 connectionstring 中的相对路径出现几个奇怪的错误之后,我觉得有必要在这里发布这个。
When using "|DataDirectory|" or "~" you are not allowed to step up and out using "../" !
使用“|DataDirectory|”时 或 "~" 你不能使用 "../" 来加强和退出!
Example is using several projects accessing the same localdb file placed in one of the projects.
示例是使用多个项目访问放置在其中一个项目中的相同 localdb 文件。
" ~/../other" and " |DataDirectory|/../other" will fail
" ~/../other" 和 " |DataDirectory|/../other" 将失败
Even if it is clearly written at MSDN herethe errors it gave where a bit unclear so hard to find and could not find it here at SO.
回答by william
<?xml version="1.0"?>
<configuration>
<appSettings>
<!--FailIfMissing=false -->
<add key="DbSQLite" value="data source=|DataDirectory|DB.db3;Pooling=true;FailIfMissing=false"/>
</appSettings>
</configuration>
回答by Sobhan
In your config file give the relative path
在你的配置文件中给出相对路径
ConnectionString = "Data Source=|DataDirectory|\Database.sdf";
Change the DataDirectory to your executable path
将 DataDirectory 更改为您的可执行路径
string path = AppDomain.CurrentDomain.BaseDirectory;
AppDomain.CurrentDomain.SetData("DataDirectory", path);
If you are using EntityFramework, then you can set the DataDirectory path in your Context class
如果您使用 EntityFramework,则可以在 Context 类中设置 DataDirectory 路径
回答by pat
I did this in the web.config file. I added to Sobhan's answer, thanks btw.
我在 web.config 文件中做了这个。我添加了 Sobhan 的回答,顺便说一句,谢谢。
<connectionStrings>
<add name="listdb" connectionString="Data Source=|DataDirectory|\db\listdb.sdf"/>
</connectionStrings>
Where "db" becomes my database directory instead of "App_Data" directory.
其中“db”成为我的数据库目录而不是“App_Data”目录。
And opened normally with:
并正常打开:
var db = Database.Open("listdb");
var db = Database.Open("listdb");
回答by Billy Raseman
I had the same issue trying to specify the relative file path for a database connected to a Windows Forms application. I was able to resolve the issue by following the directions for adding a data source to Windows Forms from Microsoft (e.g., for connecting an Access database).
我在尝试为连接到 Windows 窗体应用程序的数据库指定相对文件路径时遇到了同样的问题。我能够按照从 Microsoft 向 Windows 窗体添加数据源的说明(例如,用于连接 Access 数据库)来解决该问题。
By using this method, Visual Studio will set the relative file paths to your database for you instead of trying to set it manually. If your database is external to your application, it will create a copy of the database and add it to your application in the proper location. Although you can manually alter you connection string in App.config and/or Settings.settings or within one of your scripts, I've found this method to be error prone. Instead, I've found it best to follow the Microsoft instructions, in general.
通过使用此方法,Visual Studio 将为您设置数据库的相对文件路径,而不是尝试手动设置它。如果您的数据库在您的应用程序外部,它将创建数据库的副本并将其添加到您的应用程序的适当位置。尽管您可以在 App.config 和/或 Settings.settings 或您的脚本之一中手动更改连接字符串,但我发现此方法容易出错。相反,我发现通常最好遵循 Microsoft 说明。