【问题标题】:.net 3.5: To read connectionstring from app.config?.net 3.5:从 app.config 读取连接字符串?
【发布时间】:2010-12-22 07:46:32
【问题描述】:

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

平台是.net 3.5

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

【问题讨论】:

    标签: .net connection app-config


    【解决方案1】:

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

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

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

    【讨论】:

      【解决方案2】:

      在配置中:

      <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();
              }
      

      【讨论】:

        【解决方案3】:

        请查看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 的程序集引用

        【讨论】:

        • 我进行了广泛搜索,但找不到您所引用的教程的更新链接。您会碰巧有更新的链接吗?
        • @ecoe 我在Wayback Machine找到它
        【解决方案4】:

        这就是我所做的。

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

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

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

        结果是:

        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;
                }
            }
        }
        

        我希望这会有所帮助。

        【讨论】:

          猜你喜欢
          • 2023-04-04
          • 2011-09-26
          • 1970-01-01
          • 2014-09-16
          • 2013-11-08
          • 2012-02-19
          • 2013-09-13
          • 2013-02-01
          相关资源
          最近更新 更多