这篇文章主要介绍了C#怎么读写自定义的Config文件的相关知识,内容详细易懂,操作简单快捷,具有一定借鉴价值,相信大家阅读完这篇C#怎么读写自定义的Config文件文章都会有所收获,下面我们一起来看看吧。
可以使用VS自带的添加功能,例如
当然也可以新建一个文本文档,然后改后缀名,再加入内容,都是一样的。
我在软件的根目录里新建了一个Config文件夹,就将配置文件放在这里面了
配置文件的名字,这里可以添加多个配置文件
配置文件内容如下:
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<appSettings>
<add key="COM1" value="我是一个串口号" />
</appSettings>
</configuration>
我们新建一个 Winform 项目,然后新建一个 ConfigHelper.cs 类
using System.Configuration;
namespace Utils
{
public class ConfigHelper
{
private string ConfigPath = string.Empty;
/// <summary>
/// 获取配置文件指定的Key
/// </summary>
/// <param name="key"></param>
/// <returns></returns>
public string GetConfigKey(string key)
{
Configuration ConfigurationInstance = ConfigurationManager.OpenMappedExeConfiguration(new ExeConfigurationFileMap()
{
ExeConfigFilename = ConfigPath
}, ConfigurationUserLevel.None);
if (ConfigurationInstance.AppSettings.Settings[key] != null)
return ConfigurationInstance.AppSettings.Settings[key].Value;
else
return string.Empty;
}
/// <summary>
/// 设置配置文件指定的Key,如果Key不存在则添加
/// </summary>
/// <param name="key"></param>
/// <param name="vls"></param>
/// <returns></returns>
public bool SetConfigKey(string key, string vls)
{
try
{
Configuration ConfigurationInstance = ConfigurationManager.OpenMappedExeConfiguration(new ExeConfigurationFileMap()
{
ExeConfigFilename = ConfigPath
}, ConfigurationUserLevel.None);
if (ConfigurationInstance.AppSettings.Settings[key] != null)
ConfigurationInstance.AppSettings.Settings[key].Value = vls;
else
ConfigurationInstance.AppSettings.Settings.Add(key, vls);
ConfigurationInstance.Save(ConfigurationSaveMode.Modified);
ConfigurationManager.RefreshSection("appSettings");
return true;
}
catch
{
return false;
}
}
public ConfigHelper(string configPath)
{
ConfigPath = configPath;
}
}
}
上面的代码可以看到,我将配置文件的路径参数加入到了ConfigHelper的构造函数中去了,这样假设有个多个配置文件,直接实例化就好了。读写互相不相影响。
Form1 界面中我就添加了一个按钮,没有其他的控件,界面就不展示了,代码如下
using System;
using System.Windows.Forms;
using Utils;
namespace Test2
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private ConfigHelper ConfigHelpers = null;
private void Form1_Load(object sender, EventArgs e)
{
string configPath = Application.StartupPath + "\\Config\\SystemInfo.config";
ConfigHelpers = new ConfigHelper(configPath);
}
private void button1_Click(object sender, EventArgs e)
{
//读取Key
//string value = ConfigHelpers.GetConfigKey("COM1");
//Console.WriteLine(value);
//设置Key
bool result = ConfigHelpers.SetConfigKey("游戏名", "XX信条");
Console.WriteLine("执行完毕");
}
}
}
读取Key
string value = ConfigHelpers.GetConfigKey("COM1");
设置Key
bool result = ConfigHelpers.SetConfigKey("游戏名", "XX信条");
关于“C#怎么读写自定义的Config文件”这篇文章的内容就介绍到这里,感谢各位的阅读!相信大家对“C#怎么读写自定义的Config文件”知识都有一定的了解,大家如果还想学习更多知识,欢迎关注亿速云行业资讯频道。
亿速云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。