C# 配置文件 XML
时间: 2023-07-12 18:38:19 浏览: 106
C#中配置文件的读写xml
在C#中,可以使用XML文件作为配置文件来存储应用程序或组件的配置信息。以下是一个示例:
```xml
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<appSettings>
<add key="Setting1" value="Value1" />
<add key="Setting2" value="Value2" />
</appSettings>
<connectionStrings>
<add name="Database" connectionString="Data Source=ServerName;Initial Catalog=DatabaseName;Integrated Security=True" providerName="System.Data.SqlClient" />
</connectionStrings>
</configuration>
```
在上面的示例中,`appSettings`节点用于存储应用程序的设置,`connectionStrings`节点用于存储数据库连接字符串。可以使用`ConfigurationManager.AppSettings`和`ConfigurationManager.ConnectionStrings`类来访问这些设置。
以下是一个示例代码:
```csharp
// 获取设置值
string setting1Value = ConfigurationManager.AppSettings["Setting1"];
string connectionString = ConfigurationManager.ConnectionStrings["Database"].ConnectionString;
// 修改设置值
Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
config.AppSettings.Settings["Setting1"].Value = "New Value";
config.Save(ConfigurationSaveMode.Modified);
ConfigurationManager.RefreshSection("appSettings");
```
注意,如果要修改配置文件,需要在应用程序的配置文件中设置`configSections`节点:
```xml
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<configSections>
<section name="appSettings" type="System.Configuration.AppSettingsSection, System.Configuration"/>
<section name="connectionStrings" type="System.Configuration.ConnectionStringsSection, System.Configuration"/>
</configSections>
<!-- ... -->
</configuration>
```
希望对你有所帮助!
阅读全文