Trying to get String from App.config File - c#

I'm desperately trying to make a working app.config file in which I want to save the connection strings for my database connections.
This is my app.config file:
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<appSettings>
<add key="Con" value="User Id = *******;password=**;data source= (DESCRIPTION =(ADDRESS = (PROTOCOL = TCP)(HOST = ******)(PORT = 1525))(CONNECT_DATA =(SERVER = DEDICATED)(SID = emtst)))"/>
</appSettings>
</configuration>
And when I try to read it here:
string connStr = ConfigurationManager.AppSettings["Con"];
this.odacManager = new ODACManager(connStr);
I just get an empty string. I'm using System.Configuration.
I've also tried to use
ConfigurationManager.Connectionstring["Con"].ConnectionString
but that also didn't work.

You should be using the <connectionStrings> element in your config file:
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<connectionStrings>
<add name="Con"
connectionString="User Id=*******;password=**;data source=(DESCRIPTION =(ADDRESS = (PROTOCOL = TCP)(HOST = ******)(PORT = 1525))(CONNECT_DATA =(SERVER = DEDICATED)(SID = emtst)))"/>
</connectionStrings>
</configuration>
and then read it out as:
string connStr = ConfigurationManager.ConnectionStrings["Con"].ConnectionString;
Update:
In .NET, class library projects cannot have their own config files - they won't be used and won't be evaluated at runtime.
If your class library needs any configuration, you need to put that configuration into the host application's app.config (or web.config) so that the class library can find it there (and use it).

try
System.Configuration.ConfigurationSettings.AppSettings["Con"].ToString();

Related

connectionStrings from Multiple files App.config

I'm need to read connectionStrings from different files .config
file1.ddl.config
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<connectionStrings>
<add name="" connectionString=""/>
</connectionStrings>
</configuration>
file2.ddl.config
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<connectionStrings>
<add name="" connectionString=""/>
</connectionStrings>
</configuration>
I try ConfigurationManager.ConnectionStrings["NAME"].ConnectionString but i recive "Object not set" and i can't use ConfigurationSettings.AppSettings because it´s deprecated
enter image description here
U can try add the key's in the same file.
string exePath = System.Reflection.Assembly.GetExecutingAssembly().Location; //exePath
Configuration config = ConfigurationManager.OpenExeConfiguration(exePath);
ConnectionStringsSection section = config.GetSection("connectionStrings") as ConnectionStringsSection;
string connectionFile = section.ConnectionStrings["nameConnection"].ConnectionString;

Read separate web.config file outside the application folder

I need to read web.config file, outside the application's folder (located in any other directory).
I tried this code:
string filePath = #"C:\Users\Idrees\Downloads\New folder\Web.config";
Configuration c1 = ConfigurationManager.OpenExeConfiguration(filePath);
var value1 = c1.AppSettings.Settings["Key1"].Value;
But it is giving me the error:
Object reference not set to an instance of an object.
Because here, c1.AppSettings is an object, but c1.AppSettings.Settings contains not items (hence 0 Count). It is not really loading the AppSettings keys. When trying to read any Key from Settings collection, it gives this error.
Is there any way how to load AppSettings keys from a web.config file outside the application folder.
If I put same file within application folder, then it reads the keys successfully.
This is my sample config file's content:
<?xml version="1.0" encoding="utf-8"?>
<!--
For more information on how to configure your ASP.NET application, please visit
http://go.microsoft.com/fwlink/?LinkId=169433
-->
<configuration>
<connectionStrings>
<!--here goes my connection strings-->
</connectionStrings>
<appSettings>
<add key="Key1" value="Value1" />
<add key="Key2" value="Value2" />
<add key="Key3" value="Value3" />
</appSettings>
</configuration>
I have a web application already running on my server. And I need to develop a small utility which has to do some job in database, and I don't want to write db credentials or connection string(and some other additional app-settings) in each application, I want it to read same thing from web.config.
You can using ConfigurationManager to read arbitrary configuration files by opening a mapped exe configuration as follows:
var filePath = #"C:\Users\Idrees\Downloads\New folder\Web.config";
var fileMap = new ExeConfigurationFileMap { ExeConfigFilename = filePath };
var configuration = ConfigurationManager.OpenMappedExeConfiguration(fileMap, ConfigurationUserLevel.None);
var value = configuration.AppSettings.Settings["Key1"].Value;
As I understand from your comment you want some kind of shared configuration accross multiple app on the same computer. You may consider using external file like this :
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<startup>
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5" />
</startup>
<connectionStrings configSource="config\connString01.config"/>
<appSettings file="config\config01.config">
<add key="Var3" value="Var3 value from main config file"/>
</appSettings>
in above .config example connectionStrings is sourced from an other file. Below an example what can be such an external config file:
<connectionStrings>
<add name="SQLConnectionString01" connectionString="Data Source=sourcename01;Initial Catalog=cat01;Persist Security Info=True;Integrated Security=true;"/>
</connectionStrings>
Read documentation: ConfigurationManager.OpenExeConfiguration on MSDN
public static Configuration OpenExeConfiguration(
string exePath
)
This is EXE path

C# connection string - Get from config section

Here is a snippet of my app.config file.
<MyProject>
<ConnectionStrings>
...
<Operational providerType="SqlServer" provider="" dataSource="<ServerName>" initialCatalog="<DBName>" security="" userName="<SomeUser>" password="<Password>" />
...
</ConnectionStrings>
</MyProject>
In my C# code, I have this value available in some variable, like...
string OperationalConnectionConfiurationPath = "MyProject/ConnectionStrings/Operational";
How can I get my SqlConnection object out of this?
connectionStrings are a child of the configuration section. Get rid of that <MyProject>stuff.
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<connectionStrings>
<add name="Operational" connectionString="Data Source=SERVER_NAME;Initial Catalog=DB_NAME;User Id=USER_ID;Password=PASSWORD;" providerName="System.Data.SqlClient" />
</connectionStrings>
</configuration>
You can get the connection string by:
using System.Configuration;
var connectionString = ConfigurationManager.ConnectionStrings["Operational"].ConnectionString;

Change connection strings in Winforms

I am developing win forms and i have App config file .How can I write to connection strings section of app config file?
My current App.Config file is
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<connectionStrings>
<add name="MyDbConnection" connectionString="" providerName="System.Data.OleDb" />
</connectionStrings>
</configuration>
and my C# code to change the Connection String is
var Config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
var connectionStringsSection = (ConnectionStringsSection)Config.GetSection("connectionStrings");
ConfigurationManager.ConnectionStrings["MyDbConnection"].ConnectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + FilePath + "";
Config.Save();
ConfigurationManager.RefreshSection("connectionStrings");
however Exception is generated at 3rd Line it is
configuration error exception this configuration is read only
The code to change connection strings is called from an external class.I dont know where should i place the code to override IsReadonly() method .
Also app config does not have code behind file.
App.config
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<connectionStrings>
<add name="MyDBConnectionString" providerName="System.Data.SqlClient"
connectionString="Data Source=localhost;Initial Catalog=MySQLServerDB; Integrated Security=true" />
</connectionStrings>
</configuration>
When you save your connection string in App.config file you can use System.Configuration.ConfigurationManager class to read this connection string in code.
ConnectionStringSettings conSettings = ConfigurationManager.ConnectionStrings["MyDBConnectionString"];
ConnectionStringsSettings class provides properties to read connection string settings in your program as follows:
string name = conSettings.Name;
string providerName = conSettings.ProviderName;
string connectionString = conSettings.ConnectionString;
To write your connection string in App.config file you can use:
Create two settings, example: AppConnectionString (type: string) and ServerConnectionString (type: ConnectionString)
Modify settings code, on get property of ServerConnectionString setting change the return value to AppConnectionString.
By doing this you can modify, save, or reload AppConnectionString setting, and when you refer to ServerConnectionString on your application, it will return AppConnectionString setting. TRY IT.

Change app.config connection string depending on PC

I'm doing a c# course at university, and now I'm beginning linQ to xml, linQ to Sql-Server, etc.
I work with the example projects in two PCs (university PC and office PC)
Is there an easy way to change connection string (from app.config) at runtime, or designtime (using a constant in main.cs) so I can use a connection string at university, and a connection string at the office easily?
Thanks a lot in advance,
You could try something like:
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<appSettings>
<add key="Environment" value="Home"/>
</appSettings>
<connectionStrings>
<add name="Work" connectionString="..."/>
<add name="Home" connectionString="..."/>
</connectionStrings>
</configuration>
and, later:
string environment = ConfigurationManager.AppSettings["Environment"];
ConfigurationManager.ConnectionStrings[environment].ConnectionString;
Another way of doing it:
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<connectionStrings>
<add name="HomeEnvironment"
connectionString="Data Source=**HOME-COMPUTER**\SQLEXPRESS;Initial Catalog=**HomeDatabase**;Integrated Security=True;"
providerName="System.Data.SqlClient" />
<add name="WorkEnvironment"
connectionString="DataSource=**WORK-COMPUTER**\SQLEXPRESS;Initial Catalog=**WorkDatabase**;Integrated Security=True;"
providerName="System.Data.SqlClient"/>
</connectionStrings>
</configuration>
and use it like this:
var environment = Environment.MachineName == "HOME-COMPUTER" ? "HomeEnvironment" : "WorkEnvironment";
var connectionString = ConfigurationManager.ConnectionStrings[environment].ConnectionString;
var dbContext = new **Databasename**ContextDataContext(connectionString);
Bold strings should be customised as required

Categories

Resources