如何使用C#中的app.config文件来定义一个连接字符串 [英] how to define a connection string using an app.config file in C#

查看:345
本文介绍了如何使用C#中的app.config文件来定义一个连接字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

目前我手动定义在我的C#代码我的连接字符串:

Currently i manually define my connection string in my C# code:

string ConnectionString = "Data Source=C;Initial Catalog=tickets;Integrated Security=True";
SqlConnection Conn = new SqlConnection(ConnectionString);
Conn.Open();

在我的项目我有一个app.config文件,我可以看到它有一个连接字符串。
它看起来像这样:<?/ p>

In my project i have an app.config file and i can see that it has a connection string. It looks like this:

<?xml version="1.0"?>
<configuration>
<configSections>
</configSections>
<connectionStrings>
    <add name="ticketNotification.Properties.Settings.ticketsConnectionString"
        connectionString="Data Source=C;Initial Catalog=tickets;Integrated Security=True"
        providerName="System.Data.SqlClient" />
</connectionStrings>
<startup><supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.0"/></startup></configuration>

如何定义基于同一文件夹中app.config文件作为我的应用程序的连接字符串?

How can i define the connection string based on the app.config file in the same folder as my application?

推荐答案

要从您使用位于System.Configuration命名空间中的类ConfigurationManager中app.config文件获取连接字符串。

To get connection strings from the app.config file you use the class ConfigurationManager located in the System.Configuration namespace.

要获得通过名称连接字符串,并创建一个基于它的连接,可以使用下面的代码:

To get the connection string by name and create a connection based on it, you can use the following code:

SqlConnection conn = new SqlConnection(
      ConfigurationManager.ConnectionStrings[
         "ticketNotification.Properties.Settings.ticketsConnectionString"]
             .ConnectionString);

您可以阅读更多关于此这里(MSDN文档):
http://msdn.microsoft.com/en-us/library/ms254494 (v = vs.110)的.aspx

You can read more about this here (MSDN Documentation): http://msdn.microsoft.com/en-us/library/ms254494(v=vs.110).aspx

确保您的项目包含到System.Configuration的引用,否则ConfigurationManager中
将不可用System.Configuration命名空间中。

Ensure your project holds a reference to System.Configuration, otherwise ConfigurationManager will not be available in the System.Configuration namespace.

问候。

这篇关于如何使用C#中的app.config文件来定义一个连接字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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