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

时间:2009-12-02 07:53:58

标签: .net connection app-config

如何使用.net api?

从app.config文件中读取连接字符串信息

平台是.net 3.5

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

4 个答案:

答案 0 :(得分:13)

请参阅Reading Connection Strings in Web.Config and App.Config and Enterprise Library DAAB Settings(在Wayback Machine上原来的内容已被删除)

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

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

答案 1 :(得分:4)

在配置中:

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

在C#代码中:

    using System.Configuration;

...

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

更好的方法是定义一个函数并在代码中的任何地方使用它:

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

答案 2 :(得分:2)

如果name是表示连接字符串名称的字符串值:

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

在您的示例中,您没有为name提供值,因此您必须在它工作之前执行此操作。

答案 3 :(得分:0)

这就是我所做的。

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

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

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

结果是: `     使用系统;     使用System.Configuration;     使用System.Collections.Generic;     使用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;
        }
    }
}

`

我希望这会有所帮助。