c# 读取App.config
时间: 2023-06-28 22:09:59 浏览: 47
在 C# 中,可以使用 `System.Configuration.ConfigurationManager` 类来读取 `App.config` 文件中的配置项。
下面是一个示例代码:
```csharp
using System.Configuration;
// 读取配置项
string connectionString = ConfigurationManager.ConnectionStrings["MyConnectionString"].ConnectionString;
// 读取应用程序设置
string settingValue = ConfigurationManager.AppSettings["MySetting"];
```
其中,`ConfigurationManager.ConnectionStrings` 属性可以获取 `App.config` 文件中的连接字符串,而 `ConfigurationManager.AppSettings` 属性可以获取应用程序设置。
需要注意的是,在读取配置项或应用程序设置前,需要在应用程序中添加对 `System.Configuration` 命名空间的引用。
相关问题
C# 读取app.config
在 C# 中,可以使用 System.Configuration.ConfigurationManager 类来读取 app.config 或者 web.config 文件中的配置信息。这个类是 .NET Framework 中的一部分,可以帮助我们读取和写入配置文件中的键值对。
以下是读取 app.config 文件中的配置信息的步骤:
1. 在代码中添加对 System.Configuration 命名空间的引用,例如:using System.Configuration;
2. 使用 ConfigurationManager 类的静态属性 AppSettings 来读取 app.config 文件中的键值对,例如:
```
string value = ConfigurationManager.AppSettings["key"];
```
其中,"key" 是需要读取的键名,value 是对应的值。
3. 如果需要读取连接字符串,可以使用 ConfigurationManager 类的静态属性 ConnectionStrings,例如:
```
string connectionString = ConfigurationManager.ConnectionStrings["connectionStringName"].ConnectionString;
```
其中,"connectionStringName" 是连接字符串的名称,connectionString 是对应的连接字符串。
需要注意的是,读取 app.config 文件中的配置信息时,需要将配置信息写在 appSettings 或 connectionStrings 节点下,否则将无法读取。另外,如果使用的是 web.config 文件,则需要将上述代码中的 ConfigurationManager 替换为 System.Web.Configuration.WebConfigurationManager。
用C#写入app.config
在 C# 中,可以使用 `System.Configuration.ConfigurationManager` 类来读取和写入 `app.config` 文件的值。下面是一个示例,演示如何将一个值写入 `app.config` 文件中:
```csharp
using System.Configuration;
// 获取配置文件
var config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
// 修改或添加键值对
config.AppSettings.Settings["key"].Value = "value";
// 保存配置文件更改
config.Save(ConfigurationSaveMode.Modified);
// 强制重新加载配置文件以使更改生效
ConfigurationManager.RefreshSection("appSettings");
```
在上面的代码中,我们使用 `ConfigurationManager.OpenExeConfiguration` 方法打开 `app.config` 文件并将其保存到变量 `config` 中。然后我们使用 `config.AppSettings.Settings` 属性来修改或添加键值对。
最后,我们使用 `config.Save` 方法将更改保存回 `app.config` 文件中,并使用 `ConfigurationManager.RefreshSection` 方法强制重新加载配置文件以使更改生效。
请注意,如果你在 Visual Studio 中运行此代码,则必须以管理员身份运行 Visual Studio。否则,你将无法将更改保存回 `app.config` 文件中。