winform读取配置文件
1、在电脑中设置配置文件:
安装软件后,电脑C盘会增加使用量,其中原因之一是软件会在C盘存放一些数据,那在Winform中如何对C盘进行操作?
要操作C盘首先得获取该路径,C#中获取特殊路径如下:
(还有很多枚举值)
Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData)
获取到路径就可以自定义文件和配置数据进行操作了。
2、读取默认配置文件:
Winform开发中经常需要在配置文件进行数据的读取,众所周知,Winform程序有一个默认配置文件,如何读取可以参考以下方式:
using System;
using System.Configuration;
using System.IO;
using System.Windows.Forms;
using System.Xml;
namespace Extension
{
/// <summary>
/// 操作配置文件(修改)
/// </summary>
public class AppSettings
{
/// <summary>
/// 设置配置文件AppSettings节点的键名和值并持久化到文件
/// </summary>
public static void SetConfig(string key, string value)
{
try
{
var path = Path.GetFileNameWithoutExtension(Application.ExecutablePath);
Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
AppSettingsSection section = config.AppSettings;
if (section != null && section.Settings[key] != null)
{
section.Settings[key].Value = value;
}
else
{
section.Settings.Add(new KeyValueConfigurationElement(key, value));
}
config.Save(ConfigurationSaveMode.Modified);
ConfigurationManager.RefreshSection("appSettings");
}
catch (Exception ex)
{
throw ex;
}
}
}
/// <summary>
/// 操作配置文件(读取)
/// </summary>
public class AppSettings<T> : AppSettings
{
public static T GetConfig(string key)
{
try
{
Type type = typeof(T);
object result = null;
object val = null;
val = ConfigurationManager.AppSettings[key];
if (type == typeof(int))
result = Convert.ToInt32(val);
else if (type == typeof(string))
result = Convert.ToString(val);
else if (type == typeof(double))
result = Convert.ToDouble(val);
else
result = Convert.ChangeType(val, type);
return (T)result;
}
catch
{
return default(T);
}
}
}
}
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· Manus的开源复刻OpenManus初探
· AI 智能体引爆开源社区「GitHub 热点速览」
· C#/.NET/.NET Core技术前沿周刊 | 第 29 期(2025年3.1-3.9)
· 从HTTP原因短语缺失研究HTTP/2和HTTP/3的设计差异