上位机学习记录(5) 日志ini 与json读取配置文件

上位机学习记录(5) 日志ini 与json读取配置文件

(一) 代码

IniConfigHelper.cs

    public  class IniConfigHelper
    {

        #region API函数声明

        [DllImport("kernel32")]
        private static extern long WritePrivateProfileString(string section, string key,
            string val, string filePath);

        //需要调用GetPrivateProfileString的重载
        [DllImport("kernel32", EntryPoint = "GetPrivateProfileString")]
        private static extern long GetPrivateProfileString(string section, string key,
            string def, StringBuilder retVal, int size, string filePath);

        [DllImport("kernel32", EntryPoint = "GetPrivateProfileString")]
        private static extern uint GetPrivateProfileStringA(string section, string key,
            string def, byte[] retVal, int size, string filePath);

        #endregion


        public static string filePath = string.Empty;

        #region 读Ini文件

        public static string ReadIniData(string Section, string Key, string NoText)
        {
            return ReadIniData(Section, Key, NoText, filePath);
        }
        public static string ReadIniData(string Section, string Key, string NoText, string iniFilePath)
        {
            if (File.Exists(iniFilePath))
            {
                StringBuilder temp = new StringBuilder(1024);
                GetPrivateProfileString(Section, Key, NoText, temp, 1024, iniFilePath);
                return temp.ToString();
            }
            else return String.Empty;
        }

        #endregion

        #region 写Ini文件

        public static bool WriteIniData(string Section, string Key, string Value)
        {
            return WriteIniData(Section, Key, Value, filePath);
        }

        public static bool WriteIniData(string Section, string Key, string Value, string iniFilePath)
        {
            if (File.Exists(iniFilePath))
            {
                long OpStation = WritePrivateProfileString(Section, Key, Value, iniFilePath);
                if (OpStation == 0)
                    return false;
                else return true;
            }
            else return false;
        }
        #endregion


        #region 获取所有的Sections
        /// <summary>
        /// 获取所有的Sections
        /// </summary>
        /// <param name="iniFilename">文件路径</param>
        /// <returns>Sections集合</returns>
        public static List<string> ReadSections(string iniFilename)
        {
            List<string> result = new List<string>();
            Byte[] buf = new Byte[65536];
            uint len = GetPrivateProfileStringA(null, null, null, buf, buf.Length, iniFilename);
            int j = 0;
            for (int i = 0; i < len; i++)
                if (buf[i] == 0)
                {
                    result.Add(Encoding.Default.GetString(buf, j, i - j));
                    j = i + 1;
                }
            return result;
        }

        #endregion

        #region 获取指定Section下的所有Keys
        /// <summary>
        /// 获取指定Section下的所有Keys
        /// </summary>
        /// <param name="SectionName">SectionName</param>
        /// <param name="iniFilename">文件路径</param>
        /// <returns>Keys集合</returns>
        public static List<string> ReadKeys(string SectionName, string iniFilename)
        {
            List<string> result = new List<string>();
            Byte[] buf = new Byte[65536];
            uint len = GetPrivateProfileStringA(SectionName, null, null, buf, buf.Length, iniFilename);
            int j = 0;
            for (int i = 0; i < len; i++)
                if (buf[i] == 0)
                {
                    result.Add(Encoding.Default.GetString(buf, j, i - j));
                    j = i + 1;
                }
            return result;
        }
        #endregion
    }

JSONHelper.cs

    public class JSONHelper
    {

        /// <summary>
        /// 实体对象转换成JSON字符串
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="x"></param>
        /// <returns></returns>
        public static string EntityToJSON<T>(T x)
        {
            string result = string.Empty;

            try
            {
                result = JsonConvert.SerializeObject(x);
            }
            catch (Exception)
            {
                result = string.Empty;
            }
            return result;

        }

        /// <summary>
        /// JSON字符串转换成实体类
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="json"></param>
        /// <returns></returns>
        public static T JSONToEntity<T>(string json)
        {
            T t = default(T);
            try
            {
                t = (T)JsonConvert.DeserializeObject(json, typeof(T));
            }
            catch (Exception)
            {
                t = default(T);
            }

            return t;
        }
    }

JSONHelper用法

  ///json转换成BasicParam对象
  BasicParam basicParam = JSONHelper.JSONToEntity<BasicParam>(jsonbasic);

  ///将BasicParam转换成JSON字符串
  string json = JSONHelper.EntityToJSON(basicParam);

(二)使用泛型的方法快速设置与存储数值

       #region 对象属性操作

        /// <summary>
        /// 通过属性名称获取值
        /// </summary>
        /// <typeparam name="T">对象类型</typeparam>
        /// <param name="obj">对象</param>
        /// <param name="propertyName">属性名称</param>
        /// <returns>返回值</returns>
        private string GetObjectPropertyValue<T>(T obj, string propertyName)
        {
            try
            {
                Type type = typeof(T);

                PropertyInfo property = type.GetProperty(propertyName);

                if (property == null) return string.Empty;

                object val = property.GetValue(obj, null);

                return val?.ToString();
            }
            catch (Exception ex)
            {

                LogHelper.Info("通过属性名称获取值", ex);
                return null;
            }
        }

        /// <summary>
        /// 通过属性名称设置值
        /// </summary>
        /// <typeparam name="T">对象类型</typeparam>
        /// <param name="obj">对象</param>
        /// <param name="propertyName">属性名称</param>
        /// <param name="value">值</param>
        /// <returns>是否成功</returns>
        private bool SetObjectPropertyValue<T>(T obj, string propertyName, string value)
        {
            try
            {
                Type type = typeof(T);

                object t = Convert.ChangeType(value, type.GetProperty(propertyName).PropertyType);

                type.GetProperty(propertyName).SetValue(obj, t, null);

                return true;

            }
            catch (Exception ex)
            {
                LogHelper.Info("通过属性名称设置值", ex);
                return false;
            }
        }
        #region 对象属性操作

        /// <summary>
        /// 通过属性名称获取值
        /// </summary>
        /// <typeparam name="T">对象类型</typeparam>
        /// <param name="obj">对象</param>
        /// <param name="propertyName">属性名称</param>
        /// <returns>返回值</returns>
        private string GetObjectPropertyValue<T>(T obj, string propertyName)
        {
            try
            {
                Type type = typeof(T);

                PropertyInfo property = type.GetProperty(propertyName);

                if (property == null) return string.Empty;

                object val = property.GetValue(obj, null);

                return val?.ToString();
            }
            catch (Exception ex)
            {

                LogHelper.Info("通过属性名称获取值", ex);
                return null;
            }
        }

        /// <summary>
        /// 通过属性名称设置值
        /// </summary>
        /// <typeparam name="T">对象类型</typeparam>
        /// <param name="obj">对象</param>
        /// <param name="propertyName">属性名称</param>
        /// <param name="value">值</param>
        /// <returns>是否成功</returns>
        private bool SetObjectPropertyValue<T>(T obj, string propertyName, string value)
        {
            try
            {
                Type type = typeof(T);

                object t = Convert.ChangeType(value, type.GetProperty(propertyName).PropertyType);

                type.GetProperty(propertyName).SetValue(obj, t, null);

                return true;

            }
            catch (Exception ex)
            {
                LogHelper.Info("通过属性名称设置值", ex);
                return false;
            }
        }


        #endregion

image-20230317011344292

        /// <summary>
        /// 加载参数,这个所有的控件都在一个tabPage上
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="tabPage"></param>
        /// <param name="obj"></param>
        private void LoadParam<T>(TabPage tabPage, T obj)
        {
            foreach (var item in tabPage.Controls)
            {
                if (item is NumericUpDown numeric)
                {

                    //拿到属性名称
                    string propertyName = numeric.Name;

                    //通过属性拿到值
                    string value = GetObjectPropertyValue(obj, propertyName);

                    if (value != null && value.Length > 0)
                    {
                        if (decimal.TryParse(value, out decimal val))
                        {
                            numeric.Value = val;
                        }
                    }
                }
                else if (item is ComboBox cmb)
                {
                    //拿到属性名称
                    string propertyName = cmb.Name;

                    cmb.Text = GetObjectPropertyValue(obj, propertyName);
                }
            }
        }

        /// <summary>
        /// 修改参数
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="paramType"></param>
        /// <param name="obj"></param>
        private void ModifyParam<T>(string paramType, T obj)
        {

            StringBuilder sb = new StringBuilder();

            foreach (var item in this.MainTab.SelectedTab.Controls)
            {
                if (item is NumericUpDown numeric)
                {
                    //获取属性名称
                    string propertyName = numeric.Name;

                    //获取对象里的值
                    string value = GetObjectPropertyValue(obj, propertyName);

                    if (numeric.Value.ToString() != value)
                    {
                        //添加修改记录
                        sb.Append(numeric.Tag.ToString() + "修改为:" + numeric.Value.ToString() + " ");

                        SetObjectPropertyValue(obj, propertyName, numeric.Value.ToString());
                    }
                }
                else if (item is ComboBox cmb)
                {
                    //获取属性名称
                    string propertyName = cmb.Name;

                    //获取对象里的值
                    string value = GetObjectPropertyValue(obj, propertyName);

                    if (cmb.Text != value)
                    {
                        //添加修改记录
                        sb.Append(cmb.Tag.ToString() + "修改为:" + cmb.Text.ToString() + " ");

                        SetObjectPropertyValue(obj, propertyName, cmb.Text);
                    }
                }          
            }

            if (sb.ToString().Length > 0)
            {
                OperationResult result = paramType == "基础参数" ? motionEx.SaveBasicParam() : motionEx.SaveAdvancedParam();

                if (result.IsSuccess)
                { 
                    if (!SystemLogService.AddSystemLog(new SystemLog(sb.ToString(), "触发", AlarmType.操作记录, Program.sysAdmin.LoginName)))
                    {
                        LogHelper.Error("操作记录信息写入数据库出错");
                    }

                    new FrmConfirmSingle("参数修改", paramType + "修改成功") { TopMost = true }.ShowDialog();                
                }
                else
                {
                    new FrmConfirmSingle("参数修改", paramType + "修改失败") { TopMost = true }.ShowDialog();
                }
            }
            else
            {
                new FrmConfirmSingle("参数修改", "参数未做任何修改") { TopMost = true }.ShowDialog();
            }

        }
posted @ 2023-03-17 02:01  聆听微风  阅读(125)  评论(0编辑  收藏  举报