Accessing Connection Strings Stored in App.config
This guide demonstrates how to retrieve a connection string from your application's App.config
file using C#. The following code snippet shows the correct method:
<code class="language-csharp">string connectionString = System.Configuration.ConfigurationManager.ConnectionStrings["Test"].ConnectionString;</code>
This line directly accesses the connection string named "Test" within the ConnectionStrings
section of your App.config
file.
To use this code, ensure you've included the necessary namespace:
<code class="language-csharp">using System.Configuration;</code>
And remember, your project must have a reference to System.Configuration.dll
. Failure to include this reference will prevent the code from compiling.
The common error "Object reference not set to an instance of an object" usually arises from attempting to access a property or method of a null object. In the context of database connections, this often means the ConnectionFactory
(or a similar object) hasn't been properly initialized before being used. The method above avoids this by directly accessing the connection string from the configuration file.
The above is the detailed content of How to Retrieve a Connection String from App.config in C#?. For more information, please follow other related articles on the PHP Chinese website!