I have the following connection string declared in my app.config
file:
<connectionStrings>
<add name="SqlConnectionString" connectionString="Data Source=xxx.xx.xx.xx;Initial Catalog=xxxxx;User Id=xx;Password=xxx;" providerName="System.Data.SqlClient" />
</connectionStrings>
When I try to fetch this connection string using the following C# code snippet, I get the value null
. I am not able to obtain the connection string. Is there anything wrong in the syntax?
First attempt:
var settings = ConfigurationManager.ConnectionStrings["SqlConnectionString"];
string result = settings.ConnectionString;
Second attempt:
string result = ConfigurationSettings.AppSettings["SqlConnectionString"];
Applications use connection strings to identify the server instance and database to connect to and to determine what driver, login, etc. to use to connect to the SQL Server instance. Typically, the connection string will be stored in a configuration file somewhere within the application or web server.
Connection strings in configuration files are typically stored inside the <connectionStrings> element in the app. config for a Windows application, or the web. config file for an ASP.NET application.
In order to add AppSettings. json file, right click on the Project in Solution Explorer. Then click Add, then New Item and then choose App Settings File option (shown below) and click Add button. Once the File is created, it will have a DefaultConnection, below that a new Connection String entry is added.
First, you must add the appSettings
tag
<connectionStrings>
<appSettings>
<add name="SqlConnectionString" connectionString="Data Source=xxx.xx.xx.xx;Initial Catalog=xxxxx;User Id=xx;Password=xxx;" providerName="System.Data.SqlClient" />
</appSettings>
</connectionStrings>
Second, add a reference to System.Configuration
to your project and insert a using System.Configuration
in the source.
Then, you can use ConfigurationManager.AppSettings
to access your config setting:
string result = ConfigurationSettings.AppSettings["SqlConnectionString"];
For a non-web project, and with app.config set up as in the OP here's what I usually do, since the config file changes names when the app is compiled (to yourapp.exe.config):
public static Configuration ExeConfig()
{
Assembly service = Assembly.GetAssembly(typeof(YourClass));
return ConfigurationManager.OpenExeConfiguration(service.Location);
}
Then to reference the s'th connection string:
ExeConfig().ConnectionStrings.ConnectionStrings[s].ConnectionString
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With