SQL Express 连接字符串:相对于应用程序位置的 mdf 文件位置

发布于 2024-09-15 09:05:15 字数 498 浏览 6 评论 0原文

我使用 SQL Express 数据库作为 C# 单元测试项目的一部分。我的数据库位于此处:

./Databases/MyUnitTestDB.mdf

我想在 app.config 中使用相对路径或变量,而不是将连接字符串定义为:

AttachDbFilename=C:\blah\blah\blah\yea\yea\yea\MyApplication\Databases\MyUnitTestDB.mdf 

我已经看到 |DataDirectory|< 的使用/code> 但我认为这仅适用于 Web 应用程序是否正确?

我想在应用程序配置文件中控制这一点,因为在生产中应用程序使用托管 SQL 数据库。

I am using SQL Express databases as part of a unit test project in c#. My databases is located here:

./Databases/MyUnitTestDB.mdf

I would like to use a relative path or variable in the app.config rather than having my connection string defined as:

AttachDbFilename=C:\blah\blah\blah\yea\yea\yea\MyApplication\Databases\MyUnitTestDB.mdf 

I have seen the use of |DataDirectory| but am I correct in thinking this is only applicable to web applications?

I want to control this in the application configuration file, as in production the application uses a hosted sql database.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(7

静若繁花 2024-09-22 09:05:15

谢谢大家,我综合了你们的回答。

在我的 app.config 文件中,我的连接字符串定义如下

<add name="MyConnectionString"
    connectionString="Server=.\SQLExpress;AttachDbFilename=|DataDirectory|\MyDatabase.mdf;Database=MyDatabaseForTesting;Trusted_Connection=Yes;" />

在我的单元测试类中,我使用以下命令设置 DataDirectory 属性

[TestInitialize]
public void TestInitialize()
{
    AppDomain.CurrentDomain.SetData("DataDirectory", System.IO.Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Databases"));

    // rest of initialize implementation ...
}

Thanks everyone, I used a combination of your responses.

In my app.config file my connection string is defined as follows

<add name="MyConnectionString"
    connectionString="Server=.\SQLExpress;AttachDbFilename=|DataDirectory|\MyDatabase.mdf;Database=MyDatabaseForTesting;Trusted_Connection=Yes;" />

In my unit test class I set the DataDirectory property using the following

[TestInitialize]
public void TestInitialize()
{
    AppDomain.CurrentDomain.SetData("DataDirectory", System.IO.Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Databases"));

    // rest of initialize implementation ...
}
牵强ㄟ 2024-09-22 09:05:15

是的,|DataDirectory| Web 应用程序,用于选择 Web 应用程序的 App_Data 目录。

在非 Web 应用程序中,根据 .NET Framework,可以使用它,也可以使用 AppDomain.SetData 进行更改,

但是您还有其他两种可能性来创建连接:

1.- 使用相对对象path:

String con ="... AttachDbFilename=Databases\MyUnitTestDB.mdf ... ";

2.- 获取应用程序路径并添加到字符串.
在 C# Windows 应用程序中,您可以使用 Application.StartupPath

 String con= " ... AttachDbFilename=" + Application.StartupPath + "\Databases\MyUnitTestDB.mdf ... ";

根据应用程序类型或启动模式,您可以获得不同的属性。例如:

  • Application.StartupPath -- 启动应用程序的 exe 应用程序的启动路径
  • Application.ExecutablePath -- 启动应用程序的 exe 应用程序的启动路径统计应用程序
    但是要使用应用程序,您需要包含未包含在控制台应用程序中的 System.Windows.Forms。

  • System.IO.Path.GetDirectoryName(
    System.Reflection.Assembly.GetExecutingAssembly().GetName().CodeBase
    ) -- 这从当前程序集“dll,exe,...”获取路径,不受应用程序类型、路径变化的影响。 .. 始终返回程序集驻留时的目录。

  • Environment.CurrentDirectory -- 当前目录。例如,如果您导航到文件夹,则可以更改此设置。

您可以在此处找到有关不同连接字符串选项的更多信息
http://www.connectionstrings.com/sql-server-2005

Yes, |DataDirectory| Web application to select the App_Data directory of the web application.

In a not web application, depending on .NET Framework, it could be used and also changed using AppDomain.SetData

But you have other two posiblities to create the connection:

1.- Use a relative path:

String con ="... AttachDbFilename=Databases\MyUnitTestDB.mdf ... ";

2.- get the application path and add to the String.
In c# Windows Application you can use Application.StartupPath

 String con= " ... AttachDbFilename=" + Application.StartupPath + "\Databases\MyUnitTestDB.mdf ... ";

Depending on the applicaiton type or launch mode you got different properties. Ex:

  • Application.StartupPath -- The start path of the exe application that starts the application
  • Application.ExecutablePath -- the start path an name of the exe application that stats the application
    But to use Application you need to include System.Windows.Forms that is not included for example into console applications.

  • System.IO.Path.GetDirectoryName(
    System.Reflection.Assembly.GetExecutingAssembly().GetName().CodeBase
    ) -- This gets the path from the current assembly "dll,exe,..." Is not affected by application type, path changes,... Always return the directory when the Assemby resides.

  • Environment.CurrentDirectory -- the current directory. This can be changed for example if you navigate into folders.

You can find more about the different connection string options here
http://www.connectionstrings.com/sql-server-2005

我最亲爱的 2024-09-22 09:05:15

我花了一整天的时间在谷歌上搜索这个问题,终于从 这个

这是我的解决方案:
1. 使用|数据目录|在连接字符串

<add name="NorthwindConnectionString" connectionString="data source=.\SQLEXPRESS;Integrated Security=SSPI;AttachDbFilename=|DataDirectory|\Northwind.mdf;User Instance=True" providerName="System.Data.SqlClient" />

2.在 ClassInitialize 中设置 DataDirectory

[ClassInitialize()]
public static void MyClassInitialize(TestContext testContext)
{
    string baseDir = AppDomain.CurrentDomain.BaseDirectory;
    int index = baseDir.IndexOf("TestResults");
    string dataDir = baseDir.Substring(0, index) + System.Reflection.Assembly.GetExecutingAssembly().GetName().Name;
    AppDomain.CurrentDomain.SetData("DataDirectory", dataDir);
}

在此处输入图像描述

I have spent a whole day googling to work this through and finally have a clue from this

Here is my solution:
1. Use |DataDirectory| in connection string

<add name="NorthwindConnectionString" connectionString="data source=.\SQLEXPRESS;Integrated Security=SSPI;AttachDbFilename=|DataDirectory|\Northwind.mdf;User Instance=True" providerName="System.Data.SqlClient" />

2.Set DataDirectory in ClassInitialize

[ClassInitialize()]
public static void MyClassInitialize(TestContext testContext)
{
    string baseDir = AppDomain.CurrentDomain.BaseDirectory;
    int index = baseDir.IndexOf("TestResults");
    string dataDir = baseDir.Substring(0, index) + System.Reflection.Assembly.GetExecutingAssembly().GetName().Name;
    AppDomain.CurrentDomain.SetData("DataDirectory", dataDir);
}

enter image description here

飘过的浮云 2024-09-22 09:05:15

我正在使用 VS2010 和 C#3.0 构建一个简单的 Windows 窗体应用程序。还使用 SQL Express 2008 RC2。

我可以在连接字符串中单独使用:|DataDirectory|MyDb.mdf,而无需更改任何其他内容。 |DataDirectory| 指向我的 .exe 文件的位置。

我认为这将是你们所有人都会尝试的第一件事,因此这就是我指定 VS 和 SQL 版本的原因。或者也许它是 C#3.0 的新功能。

我的完整连接字符串:

"Server=.\SQLExpress;AttachDbFilename=|DataDirectory|App_Data\ThumbsUpPlayer.mdf;Database=ThumbsUpPlayer;Trusted_Connection=Yes;"

请注意,我在我的应用程序中添加了一个“App_Data”文件夹,因为我习惯了该文件夹中的Db,所以VS无法识别该文件夹。

I'm building a simple Windows Forms App with VS2010 with C#3.0. Also using SQL Express 2008 RC2.

I am able to use: |DataDirectory|MyDb.mdf in the connection string alone without changing anything else. The |DataDirectory| points to the location of my .exe file.

I will think that this would be the first thing all of you would try, so that is why I'm specifying my VS and SQL version. Or maybe it is new to C#3.0.

My complete Connection String:

"Server=.\SQLExpress;AttachDbFilename=|DataDirectory|App_Data\ThumbsUpPlayer.mdf;Database=ThumbsUpPlayer;Trusted_Connection=Yes;"

Note that I have added a "App_Data" folder to my application, because I'm used to the Db in that folder, the folder is not recognised by VS.

梦里兽 2024-09-22 09:05:15

我这里没有 Visual Studio,但是:

using System.IO;
using System.Windows.Forms;

string appPath = Path.GetDirectoryName(Application.ExecutablePath);
AttachDBFilme = appPath + "\\MyUnitTestDB.mdf"

I don't have Visual Studio here, but what about:

using System.IO;
using System.Windows.Forms;

string appPath = Path.GetDirectoryName(Application.ExecutablePath);
AttachDBFilme = appPath + "\\MyUnitTestDB.mdf"
倾听心声的旋律 2024-09-22 09:05:15

我做了以下事情。希望它能帮助某人。

AppDomain.CurrentDomain.SetData("DataDirectory", System.IO.Path.GetFullPath(AppDomain.CurrentDomain.BaseDirectory + "../../App_Data"));

I did the following. Hopefully it helps someone.

AppDomain.CurrentDomain.SetData("DataDirectory", System.IO.Path.GetFullPath(AppDomain.CurrentDomain.BaseDirectory + "../../App_Data"));
牵你手 2024-09-22 09:05:15

SQL Server 连接中的动态路径

SqlConnection  con="Server=.\SQLExpress;AttachDbFilename=|DataDirectory|\MyDatabase.mdf;Database=MyDatabaseForTesting;Trusted_Connection=Yes;" ;

Dynamic Path in SQL Server Connection

SqlConnection  con="Server=.\SQLExpress;AttachDbFilename=|DataDirectory|\MyDatabase.mdf;Database=MyDatabaseForTesting;Trusted_Connection=Yes;" ;
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文