WPF手写代码配置文件——单例
public class SettingHelper { //WPF下配置文件路径 public static readonly string SettingFilePath = AppDomain.CurrentDomain.BaseDirectory + "\\Setting.ini"; //使这个构造函数私有化 private SettingHelper() { } //静态函数设为只读属性 private static class Instance { internal static readonly SettingHelper Setting = new SettingHelper(); } public static SettingHelper GetInstance() { return Instance.Setting; } #region API函数声明 [DllImport("kernel32")]//返回0表示失败,非0为成功 private static extern long WritePrivateProfileString(string section, string key, string val, string filePath); [DllImport("kernel32")]//返回取得字符串缓冲区的长度 private static extern long GetPrivateProfileString(string section, string key, string def, StringBuilder retVal, int size, string filePath); #endregion #region 读Ini文件 public string ReadIniData(string section, string key) { return ReadIniData(section, key, string.Empty); } public string ReadIniData(string section, string key, string defaultValue) { if (File.Exists(SettingFilePath)) { StringBuilder s = new StringBuilder(1024); GetPrivateProfileString(section, key, defaultValue, s, 1024, SettingFilePath); return s.ToString(); } else { return String.Empty; } } #endregion //写Ini文件 public bool WriteIniData(string section, string key, string value) { if (File.Exists(SettingFilePath)) { long OpStation = WritePrivateProfileString(section, key, value, SettingFilePath); if (OpStation == 0) { return false; } else { return true; } } else { return false; } } //给窗体初始状态赋值 private string windowState; public WindowState WindowState { get { if (string.IsNullOrWhiteSpace(windowState)) { SettingHelper st = SettingHelper.GetInstance(); windowState = st.ReadIniData("WPF", "WindowState"); } if (string.IsNullOrWhiteSpace(windowState)) { windowState = ((int)System.Windows.WindowState.Normal).ToString(); } return (WindowState)Convert.ToInt32(windowState); } set { windowState = ((int)value).ToString(); SettingHelper st = SettingHelper.GetInstance(); //SettingHelper.GetInstance 获取SettingHelper的实例 st.WriteIniData("WPF", "WindowState", windowState); } } //给窗体初始大小赋值 private string left; public double Left { get { if (string.IsNullOrWhiteSpace(left)) //IsNullOrWhiteSpace判断是否为空的字符串或空格 { SettingHelper st = SettingHelper.GetInstance(); left = st.ReadIniData("WPF", "Left"); } if (string.IsNullOrWhiteSpace(left)) { left = "20"; } return Convert.ToDouble(left); } set { left = value.ToString(); SettingHelper st = SettingHelper.GetInstance(); st.WriteIniData("WPF", "Left", left); } } private string top; public double Top { get { if (string.IsNullOrWhiteSpace(top)) { SettingHelper st = SettingHelper.GetInstance(); top = st.ReadIniData("WPF", "Top"); } if (string.IsNullOrWhiteSpace(top)) { top = "20"; } return Convert.ToDouble(top); } set { top = value.ToString(); SettingHelper st = SettingHelper.GetInstance(); st.WriteIniData("WPF", "Top", top); } } }