How to get connection string from app.config in C#
By FoxLearn 11/15/2024 10:01:57 AM 102
To retrieve a connection string from the app.config file in C#, you can use the ConfigurationManager class.
Make sure that your project references the System.Configuration
assembly.
You can add System.Configuration
to your project by right-clicking the "References" node in Solution Explorer and selecting "Add Reference...". Then, choose System.Configuration
.
In your app.config
file, define a connection string inside the <connectionStrings>
element.
For example:
<configuration> <connectionStrings> <add name="cn" connectionString="Server=.;Database=myDb;User Id=sa;Password=123@qaz;" providerName="System.Data.SqlClient"/> </connectionStrings> </configuration>
Use ConfigurationManager.ConnectionStrings
to access the connection string.
// get connection string from app.config c# string connectionString = ConfigurationManager.ConnectionStrings["cn"].ConnectionString;
Ensure that the connection string name in the ConfigurationManager.ConnectionStrings["cn"]
matches the name attribute in the app.config
.
- How to get application folder path in C#
- How to copy data to clipboard in C#
- How to mark a method as obsolete or deprecated in C#
- How to Call the Base Constructor in C#
- Deep Copy of Object in C#
- How to Catch Multiple Exceptions in C#
- How to cast int to enum in C#
- What is the difference between String and string in C#?
Categories
Popular Posts
SB Admin Template
11/17/2024
RuangAdmin Template
11/17/2024
DASHMIN Admin Dashboard Template
11/17/2024
K-WD Tailwind CSS Admin Dashboard Template
11/17/2024