读取config文件
using System.Configuration;
/******************************************************
* 模块作者: zheng
* 创建时间: 2021/6/27 20:18:15
* 功能描述: 1.用于对Winform端对EXE.config或操作vshost.exe.config文件的读写;
* 2.修改构造函数中初始化对象改变操作对象。
* 使用说明: 1.右击引用,添加System.Configuration;
* 2.使用该类时需要修改命名空间;
* 3.使用前建议向app.config添加节点,节点示例:
* <appSettings file="">
* <add key="光源连接端口" value="com1" />
* <add key="COM1" value="COM1,9600,8,None,1,已启用" />
* </appSettings>
*******************************************************/
namespace 命名空间名称
{
/// <summary>
/// 配置文件操作类
/// </summary>
class ManagerConfigFile
{
/// <summary>
/// 管理配置文件对象
/// </summary>
public static readonly Configuration MConfig;
static ManagerConfigFile()
{
//1.操作vshost.exe.config
//MConfig = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
//2.操作exe.config
string file = System.Windows.Forms.Application.ExecutablePath;
MConfig = ConfigurationManager.OpenExeConfiguration(file);
}
/// <summary>
/// 获取AppSettings中某一节点值
/// </summary>
/// <param name="key">节点名称</param>
public static string GetConfigValue(string key)
{
if (MConfig.AppSettings.Settings[key] != null)
return MConfig.AppSettings.Settings[key].Value;
else
return string.Empty;
}
/// <summary>
/// 修改配置文件,若节点不存在则添加节点
/// </summary>
/// <param name="aKey">需要修改的节点名称</param>
/// <param name="aValue">需要修改的节点的值</param>
public static void UpdateAppSettings(string aKey, string aValue)
{
if (MConfig.AppSettings.Settings[aKey] != null)
MConfig.AppSettings.Settings[aKey].Value = aValue;// 修改
else
{
AppSettingsSection ass = (AppSettingsSection)MConfig.GetSection("appSettings");
ass.Settings.Add(aKey, aValue);// 添加
}
MConfig.Save(ConfigurationSaveMode.Modified);// 保存修改
ConfigurationManager.RefreshSection("appSettings");// 强制重新载入配置文件的连接配置节
}
}
}
Xml文件读取
//命名空间
using System;
using System.Collections.Generic;
using System.IO;
using System.Xml;
class LoadXml
{
/// <summary>
/// 存储所有键值对
/// </summary>
private static readonly Dictionary<string, string> DicLanguage = new Dictionary<string, string>();
/// <summary>
/// XML文档名称(不包含扩展名)
/// </summary>
/// <param name="name"></param>
public LoadXml(string name)
{
try
{
var doc = new XmlDocument();
var address = AppDomain.CurrentDomain.BaseDirectory + $"\\{name}.xml";
if (File.Exists(address))
{
doc.Load(address);
var root = doc.DocumentElement;
if (root != null)
{
var nodeLst1 = root.ChildNodes;
foreach (XmlNode item in nodeLst1) DicLanguage.Add(item.Name, item.InnerText);
}
}
}
catch (Exception ex)
{
throw new Exception(ex.Message);
}
}
}