1.首先,配置文件(.config)是标准的XML文件。开发时可以使用配置文件来更改设置,不必重新编译程序,这样使得程序更加简洁可用。
2.下面简单完成一个实例来说明整个读取过程。
1.配置文件命名
xx.exe.config
2.对于以下配置文件,假设为test.exe.config
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<appSettings>
<add key="user" value="sa"></add>
<add key="password" value="sa"></add>
</appSettings>
</configuration>
3.对config文件的读类
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Configuration;
using System.ServiceModel;
using System.ServiceModel.Configuration;
namespace test
{
///<summary>
///返回*.exe.config文件中appSettings配置节的value项
///</summary>
///<param name="strKey"></param>
///<returns></returns>
public static string GetAppConfig(string strKey)
{
string file = System.Windows.Forms.Application.ExecutablePath;
Configuration config = ConfigurationManager.OpenExeConfiguration(file);
foreach (string key in config.AppSettings.Settings.AllKeys)
{
if (key == strKey)
{
return config.AppSettings.Settings[strKey].Value.ToString();
}
}
return null;
}
}
4.测试代码
class test
{
static void Main(string[] args)
{
try
{
string user = ConfigHelper.GetAppConfig("user");
string password = ConfigHelper.GetAppConfig("password");
Console.WriteLine(user);
Console.WriteLine(password);
Console.ReadKey();
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
}
}
5.以上就是一个完整的读取配置文件的过程。
网友评论