一、项目默认配置文件
1、app.config
在创建C#项目时,visual studio会默认在项目路径创建一个名为 App.config 的程序集配置文件,其为开发时配置参数的文件,默认记录一些配置信息,当前 .NETFramework 的版本等。
2、*.exe.config
在项目编译后,会在根目录(相应 debug 或者 release 文件夹内)生成一个名为 ” 程序名称 .exe.config “ 的配置文件。当 app.config 文件有修改时,会重新复制 app.config 文件内容到 *.exe.config 和 *.vshost.exe.config 文件中,覆盖原始内容。
*.exe.config 文件为程序实际运行时实际操作的配置文件,在程序实际运行时无论怎么更改该配置文件,下一次运行时, *.exe.config 文件都会重新复制 app.config 文件,故该配置文件更改仅用于临时配置信息更改。
3、*.vshost.exe.config
在项目编译后,会在根目录(相应 debug 或者 release 文件夹内)生成一个名为 ” 程序名称.vshost.exe.config “ 的配置文件。
*.vshost.exe.config 文件为项目调试运行时实际操作的配置文件,在项目调试期间无论怎么更改该配置文件,在下一次运行时, *.vshost.exe.config 文件都会重新复制 app.config 文件,故该配置文件更改仅用于临时配置信息更改。
二、读写配置文件
1、添加 System.Configuration 程序集文件
系统程序集文件中有能操作 Config 文件的 API库文件,在项目 “引用” 上右键,点击“添加引用” ,打开“引用管理器”窗口。
在程序集中找到 System.Configuration ,选中后点击确定。将 System.Configuration 文件添加到项目引用中。
2、Config读取操作类函数
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace FileOperationsDemo
{
public static class ReadWriteConfig
{
#region 在系统配置文件中 读/写配置相关函数
/// <summary>
/// 从 *.exe.config 或 *.vshost.exe.config 文件中读取数据,返回字符串
/// </summary>
/// <param name="Setting_name"></param>
/// <returns></returns>
public static String Read_appSetting(String Setting_name)
{
String str = "";
//获取Configuration对象
Configuration config = System.Configuration.ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
//根据Key读取<add>元素的Value
str = config.AppSettings.Settings[Setting_name].Value;
return str;
}
/// <summary>
/// 从 *.exe.config 或 *.vshost.exe.config 文件中读取数据,处理后返回List列表
/// </summary>
/// <param name="Setting_name"></param>
/// <returns></returns>
public static List<String> Read_appSetting_List(String Setting_name)
{
String str = "";
//获取Configuration对象
Configuration config = System.Configuration.ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
//根据Key读取<add>元素的Value
str = config.AppSettings.Settings[Setting_name].Value;
string[] tmp = str.Split(',');
List<string> ret_list = new List<string>();
ret_list.Clear();
for (Int32 i = 0; i < tmp.Length