.net 3.5:从 app.config 读取连接字符串?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1831291/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-03 13:36:40  来源:igfitidea点击:

.net 3.5: To read connectionstring from app.config?

.netconnectionapp-config

提问by Maddy.Shik

How to read connection string info from app.config file using .net api?

如何使用 .net api 从 app.config 文件中读取连接字符串信息?

Platform is .net 3.5

平台是.net 3.5

     <?xml version="1.0" encoding="utf-8" ?>
        <configuration>
            <connectionStrings>
                 <add connectionString="" providerName="" name=""/>
            </connectionStrings>
        </configuration> 

回答by Justin

Please see Reading Connection Strings in Web.Config and App.Config and Enterprise Library DAAB Settings(on the Wayback Machine as the original got deleted)

请参阅读取 Web.Config 和 App.Config 中的连接字符串以及企业库 DAAB 设置(在 Wayback 机器上,因为原始文件已被删除)

ConnectionStringSettings connection = ConfigurationManager.ConnectionStrings["MyConnectionString"]
string connectionString = connection.ConnectionString

You may need to add an assembly reference to System.Configuration

您可能需要将程序集引用添加到 System.Configuration

回答by SO User

In the config:

在配置中:

<add name="ConnectionName" connectionString="Data Source=xxxx\yyyy;Initial Catalog=MyDB;User ID=userName;Password=pwd" />

In C# code:

在 C# 代码中:

    using System.Configuration;

...

    string connectionString = ConfigurationManager.ConnectionStrings["ConnectionName"].ToString();

Better still would be to define a function and use it in the code everywhere:

更好的是定义一个函数并在代码中到处使用它:

public string getConnectionStringMyDB()
        {
            return ConfigurationManager.ConnectionStrings["ConnectionName"].ToString();
        }

回答by Mark Seemann

If nameis a string value that represents the name of the connection string:

Ifname是表示连接字符串名称的字符串值:

var connectionString = 
    ConfigurationManager.ConnectionStrings[name].ConnectionString;

In your example you didn't provide a value for name, so you'll have to do that before it'll work.

在您的示例中,您没有为 提供值name,因此您必须在它起作用之前这样做。

回答by John Washburn

Here is what I did.

这是我所做的。

I needed a service to start automatically and connect to a SQL Server database as part of its startup. This means the name of the DB connection string needs to be stored in the registry and that the string stored in the registry must correspond to a defined connection string. The answer was a small Winforms applet that managed the registry storage of start up parameters for the service where one of the stored parameters was the nameof the DB connection string.

我需要一个服务来自动启动并连接到 SQL Server 数据库作为其启动的一部分。这意味着数据库连接字符串的名称需要存储在注册表中,并且存储在注册表中的字符串必须与定义的连接字符串相对应。答案是一个小的 Winforms 小程序,它管理服务启动参数的注册表存储,其中存储的参数之一是数据库连接字符串的名称

I added two static functions to the database context class created by Linq. One method enumerates DB connection names defined in the settings section fo the DB project. The second method returns to me a DB context from the DB connection name provide. The registry management applet called the enumerator method in order to fill the list box and the windows service called the GetDBContextFromConnectionName()method to convert the DB Connection name retrieved from the registry into a DB context. The DB context was then used for DB access.

我在 Linq 创建的数据库上下文类中添加了两个静态函数。一种方法是枚举在 DB 项目的设置部分中定义的 DB 连接名称。第二种方法从提供的数据库连接名称返回给我一个数据库上下文。注册表管理小程序调用枚举器方法以填充列表框,Windows 服务调用该GetDBContextFromConnectionName()方法将从注册表中检索到的数据库连接名称转换为数据库上下文。然后将 DB 上下文用于 DB 访问。

These two methods were put into a class file I added to the project which had the same name as the datacontext class created by Linq.

这两个方法被放入我添加到项目中的类文件中,该文件与 Linq 创建的 datacontext 类同名。

The result was:

结果是:

using System;
using System.Configuration;
using System.Collections.Generic;
using System.Collections;

namespace RepositoryProject
{
    public partial class RepositoryDataContext
    {
        /// <summary>
        /// Return a MS SQL-LINQ DB Context given the name of the DB Connection name defined in 
        /// Properties.Settings.Default area of the SQL-Linq project.
        /// </summary>
        /// <param name="dbConnectionName">The name of the prediefined DB Connection string</param>
        /// <returns>A SQL-Linq database context </returns>
        public static RepositoryDataContext GetDBContextFromConnectionName(string dbConnectionName)
        {
            string fullConnectionString = null;

            dbConnectionName = dbConnectionName.Trim();
            if (!String.IsNullOrEmpty(dbConnectionName))
            {
                SettingsPropertyCollection allConnectionStrings = global::Cognex.TA.Framework.Properties.Settings.Default.Properties;
                SettingsProperty connectionProperty = allConnectionStrings[dbConnectionName];
                if (null != connectionProperty)
                {
                    fullConnectionString = (string) connectionProperty.DefaultValue;
                    if (String.IsNullOrEmpty(dbConnectionName))
                    {
                        string msg = "";
                        msg += String.Format( "The connection string name, {0}, exists within the settings of the RepositoryDataContext class but creates an empty DB connection string.", dbConnectionName);
                        throw new ArgumentException(msg);
                    }
                }
                else
                {
                    string msg = "";
                    msg += String.Format( "The connection string name, {0}, does not exist within the settings of the RepositoryDataContext class.", dbConnectionName);
                    throw new ArgumentException(msg);
                }
            }
            else
            {
                string msg = "";
                msg += "The connection string name to the test repository cannot be null or empty.";
                throw new ArgumentException(msg);
            }

            return new RepositoryDataContext(fullConnectionString);

        }

        /// <summary>
        /// Return a list of all the DB Connection names defined in 
        /// Properties.Settings.Default area of the SQL linq project.
        /// </summary>
        /// <returns>A list of DB Connection name</returns>
        public static List<string> GetAllDBConnectionNames()
        {
            List<string> listONames = new List<string>();

            /*
             * within the the Linq-generated code (TestRepository.designer.cs) there is an empty constructor for
             * the data context which looks similar to this:
             *
             * public TestRepositoryDataContext() :
             * base(global::Framework.Properties.Settings.Default.DefaultConnectionString, mappingSource)
             * {
                  OnCreated();
             * }
             *
             * Duplicate that assembly name here
             */
            SettingsPropertyCollection allConnectionStrings = global::Framework.Properties.Settings.Default.Properties;
            foreach(SettingsProperty entry in allConnectionStrings)
            {
                if (entry.PropertyType.ToString().Equals("System.String"))
                {
                    listONames.Add(entry.Name);
                }
            }

            return listONames;
        }
    }
}

I hope this helps.

我希望这有帮助。