Материал из .Net Framework эксперт
For programmatic access to .NET *.config files
using System;
using System.Configuration;
class MainClass
{
static void Main(string[] args)
{
AppSettingsReader ar = new AppSettingsReader();
Console.WriteLine("Here is your conn string");
Console.WriteLine(ar.GetValue("appConStr", typeof(string)));
Console.WriteLine();
int numbOfTimes = (int)ar.GetValue("intValue", typeof(int));
for(int i = 0; i < numbOfTimes; i++)
Console.WriteLine("Yo!");
}
}
/*
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<appSettings>
<add key="appConStr" value="server=localhost;uid=sa;pwd=;database=Cars" />
<add key="intValue" value="4" />
</appSettings>
</configuration>
*/
Store ConnectionStringConfig solution
using System;
using System.Data;
using System.Data.SqlClient;
using System.Configuration;
class Program
{
static void Main(string[] args)
{
foreach (ConnectionStringSettings css in ConfigurationManager.ConnectionStrings)
{
Console.WriteLine(css.Name);
Console.WriteLine(css.ProviderName);
Console.WriteLine(css.ConnectionString);
}
string sqlConnectString =ConfigurationManager.ConnectionStrings["AdventureWorks"].ConnectionString;
SqlConnection connection = new SqlConnection(sqlConnectString);
connection.Open( );
Console.WriteLine("Connection string state = {0}", connection.State);
connection.Close( );
Console.WriteLine("Connection string state = {0}", connection.State);
}
}
Use AppSettingsReader to load settings from app.config
using System;
using System.Drawing;
using System.Collections;
using System.ruponentModel;
using System.Windows.Forms;
using System.Data;
public class MainClass {
[STAThread]
static void Main()
{
System.Configuration.AppSettingsReader configurationAppSettings = new System.Configuration.AppSettingsReader();
Console.WriteLine((string)(configurationAppSettings.GetValue("label1.Text", typeof(string))));
}
}
/* app.config
<?xml version="1.0" encoding="Windows-1252"?>
<configuration>
<appSettings>
<!-- User application and configured property settings go here.-->
<!-- Example: <add key="settingName" value="settingValue"/> -->
<add key="label1.Text" value="label1" />
</appSettings>
</configuration>
*/