C#读取config文件
时间: 2023-07-05 10:08:37 浏览: 96
在C#中读取配置文件可以使用`System.Configuration`命名空间中的`ConfigurationManager`类,具体步骤如下:
1. 在项目根目录下,添加一个名为`App.config`或`Web.config`的配置文件。
2. 在配置文件中添加需要的配置项,如下所示:
```xml
<configuration>
<appSettings>
<add key="ConnectionString" value="Data Source=localhost;Initial Catalog=TestDB;Integrated Security=True"/>
<add key="MaxRetryCount" value="3"/>
</appSettings>
</configuration>
```
3. 在C#代码中使用`ConfigurationManager.AppSettings`属性获取相应的配置项,如下所示:
```csharp
using System.Configuration;
string connectionString = ConfigurationManager.AppSettings["ConnectionString"];
int maxRetryCount = int.Parse(ConfigurationManager.AppSettings["MaxRetryCount"]);
```
注意:需要在代码文件中添加`using System.Configuration`语句以引用`ConfigurationManager`类。
阅读全文
相关推荐
![cs](https://img-home.csdnimg.cn/images/20250102104920.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![application/x-rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![rar](https://img-home.csdnimg.cn/images/20241231044955.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![rar](https://img-home.csdnimg.cn/images/20241231044955.png)
![-](https://img-home.csdnimg.cn/images/20241231044930.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)