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

查看:40
本文介绍了如何在 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 文件,我可以看到它有一个连接字符串.它看起来像这样:

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?

推荐答案

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

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天全站免登陆