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);
}
}
}
}

浙公网安备 33010602011771号