使用到了ESBasic.dll,下载地址https://download.csdn.net/download/letunihao/10282332
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace WindowsFormsApplication1
{
/// <summary>
/// 系统设置。保存用户设置的数据。
/// </summary>
// 用于序列化的对象必须设置 [System.Serializable] 标签,该标签指示一个类可以序列化
[Serializable]
public class SystemSettings
{
public static string SystemSettingsFilePath = Application.StartupPath + "SystemSettings.dat";
// 定义一个静态变量来保存类的实例
private static SystemSettings singletonSettings;
/// <summary>
/// 单例模式,定义公有方法提供一个全局访问点。
/// </summary>
public static SystemSettings SingletonSettings
{
get
{
// 如果类的实例不存在则创建,
if (singletonSettings == null)
{
singletonSettings = SystemSettings.Load();
if (singletonSettings == null)
{
singletonSettings = new SystemSettings();
}
}
return singletonSettings;
}
}
// 定义私有构造函数,使外界不能创建该类实例
private SystemSettings() { }
#region AutoRun
private bool autoRun = false;
/// <summary>
/// 是否开机自动 运行
/// </summary>
public bool AutoRun
{
get { return autoRun; }
set { autoRun = value; }
}
#endregion
#region MacServerIP
private string macServerIP = "http://";
/// <summary>
/// 是否开机自动 运行
/// </summary>
public string MacServerIP
{
get { return macServerIP; }
set { macServerIP = value; }
}
#endregion
#region ExportCodelong
private int exportCodelong = 24;
/// <summary>
/// 是否开机自动 运行
/// </summary>
public int ExportCodelong
{
get
{
if (this.exportCodelong == 0)
{
this.exportCodelong = 7;
}
return exportCodelong;
}
set { exportCodelong = value; }
}
#endregion
public void Save()
{
byte[] data = ESBasic.Helpers.SerializeHelper.SerializeObject(this);
ESBasic.Helpers.FileHelper.WriteBuffToFile(data, SystemSettingsFilePath);
}
private static SystemSettings Load()
{
try
{
if (!File.Exists(SystemSettingsFilePath))
{
return null;
}
byte[] data = ESBasic.Helpers.FileHelper.ReadFileReturnBytes(SystemSettingsFilePath);
return (SystemSettings)ESBasic.Helpers.SerializeHelper.DeserializeBytes(data, 0, data.Length);
}
catch (Exception ee)
{
System.Windows.Forms.MessageBox.Show(ee.Message);
return null;
}
}
}
}
使用方法
MessageBox.Show(SystemSettings.SingletonSettings.AutoRun.ToString());
SystemSettings.SingletonSettings.AutoRun = true;
SystemSettings.SingletonSettings.Save();
下面这个默认参数用处不大,首次调用的时候,必须通过set设置一个值
private int exportCodelong = 24;
或者在get里增加以下代码,但是并不会保存到配置文件中
get
{
if (this.exportCodelong == 0)
{
this.exportCodelong = 24;
}
return exportCodelong;
}