C#生成本地配置文件
首先新建一个类,名为“GlobalSettings.cs”
直接贴代码
public static ApplyInfo ApplyInfo = new ApplyInfo(); private static XApplySetting applySetting; public static XApplySetting ApplySetting { get { if (applySetting == null) { string filePath = ApplyInfo.ApplySettingPath + "ApplySetting.xml"; if (File.Exists(filePath)) { try { applySetting = XmlHelper.XMLFlieToObject<XApplySetting>(filePath, Encoding.UTF8); } catch { File.Delete(filePath); } } if (applySetting == null) { applySetting = applySetting ?? new XApplySetting(); ApplySetting = applySetting; } } return applySetting; } set { string filePath = ApplyInfo.ApplySettingPath; //创建指定文件夹 if (!Directory.Exists(filePath)) Directory.CreateDirectory(filePath); filePath += "ApplySetting.xml"; XmlHelper.ObjectToXMLFile(value, filePath, Encoding.UTF8); applySetting = value; } }
然后再建一个类,名为ApplyInfo
代码为:
/// <summary> /// 获取软件名称 /// </summary> public string SoftwareName { get { return "CodeTools"; } } /// <summary> /// 获取应用名称 /// </summary> public string ApplyName { get { return "CodeTools"; } } /// <summary> /// 构建版本 /// </summary> public int BuildVersion { get { return 1; } } /// <summary> /// 版本日期 /// </summary> public string VersionInfo { get { return " V1.0.0"; } } /// <summary> /// 我的文档路径 /// </summary> public string ApplyMyDocuments { get => $"{Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments)}\\{ApplyName}\\{{0}}\\"; } /// <summary> /// 应用配置路径 /// </summary> public string ApplySettingPath { get => $"{string.Format(ApplyMyDocuments, "setting")}"; }
这个类完成之后再新建一个类,名为“XApplySetting.cs”
这个类中就是存一些想要存的变量了
就比如
public class XApplySetting
{
/// <summary>
/// 程序版本
/// </summary>
public int Version { get; set; }
}
这就是一个变量,接下来如何使用呢
取值比较简单:
直接定义一个变量
string username= GlobalSettings.ApplySetting.UserName;
接下来是赋值
var setting = GlobalSettings.ApplySetting;
setting.UserName = “admin”;
setting.PassWord = “123456”;
GlobalSettings.ApplySetting = setting;
完成