.net 3.5: To read connectionstring from app.config?
How to read connection string info from app.config file using .net api?
Platform is .net 3.5
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<connectionStrings>
<add开发者_StackOverflow connectionString="" providerName="" name=""/>
</connectionStrings>
</configuration>
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)
ConnectionStringSettings connection = ConfigurationManager.ConnectionStrings["MyConnectionString"]
string connectionString = connection.ConnectionString
You may need to add an assembly reference to System.Configuration
In the config:
<add name="ConnectionName" connectionString="Data Source=xxxx\yyyy;Initial Catalog=MyDB;User ID=userName;Password=pwd" />
In C# code:
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();
}
If name
is a string value that represents the name of the connection string:
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.
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 name of the DB connection string.
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.
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.
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.
精彩评论