读取配置文件,如果配置文件出错就用默认值创建一个新的的配置文件。
文件在程序的exe目录TitlePictureConfigInfo.json文件中。
using Newtonsoft.Json;
using System;
private const string defultconfigpath = "/TitlePictureConfigInfo.json";//默认的配置文件名称
///
/// 初始化程序配置文件
///
private void InitTitlePictureConfigInfo()
{
string programTitleFilePath = Application.StartupPath + defultconfigpath;
if (System.IO.File.Exists(programTitleFilePath))//判断文件是否存在
{
string readTileFileStr1 = System.IO.File.ReadAllText(programTitleFilePath);
titlePictureConfigInfo = JsonConvert.DeserializeObject(readTileFileStr1);
if (titlePictureConfigInfo == null)
{
SetDefaultConfig();
}
if (titlePictureConfigInfo.Btn_EnterSystem_FontColor == null)
{
SetDefaultConfig();
}
}
else
{
SetDefaultConfig();
}
string readTileFileStr = System.IO.File.ReadAllText(programTitleFilePath);
titlePictureConfigInfo = JsonConvert.DeserializeObject(readTileFileStr);
}
当配置文件出错就会重新创建默认的配置文件
///
/// 写入默认的配置文件
///
private void SetDefaultConfig()
{
TitlePictureConfigInfo defultConfig = new TitlePictureConfigInfo();
string defuleString = JsonConvert.SerializeObject(defultConfig);
string path = Application.StartupPath + defultconfigpath;
System.IO.File.WriteAllText(path, defuleString);
}
配置文件的对象,每多个想要配置的 项目就多一个属性,并需要给到默认值
///
/// 配置文件的对象
///
internal class TitlePictureConfigInfo
{
///
/// 内容
///
public string Title_TitleText = "XXXX_系统";
///
/// 字体
///
public string Title_Fonts = "宋体";
///
/// 字体大小
///
public int Title_FontSize = 40;
///
/// 字体颜色
///
public string Title_FontColor = "#FFFFFF";
//---------------------------------------------------------------------
///
/// 进入系统按钮上显示的文字
///
public string Btn_EnterSystem_Text = "进入系统";
///
/// 按钮字体
///
public string Btn_EnterSystem_Font = "宋体";
///
/// 按钮字体大小
///
public int Btn_EnterSystem_FontSize = 9;
///
/// 按钮字体颜色
///
public string Btn_EnterSystem_FontColor = "#FFFFFF";
//-------------------------------------------------------------------
///
/// 目标程序路径
///
public string TargetProcessPath = @"C:\Windows\System32\calc.exe";
///
/// 图片的路径
///
public string PictureBoxPath = "/pexels-stephan-seeber-1261728.png";
}