using DevExpress.Data.Browsing.Design; using System; using System.Collections; using System.Collections.Generic; using System.Configuration; using System.Data; using System.Linq; using System.Net.NetworkInformation; using System.Reflection; using System.Text; namespace ZJ_BYD.Untils { public static class ExtendMethod { /// /// DataTable转成List /// /// /// /// public static List ToDataList(this DataTable dt) { var list = new List(); var plist = new List(typeof(T).GetProperties()); foreach (DataRow item in dt.Rows) { T s = Activator.CreateInstance(); for (int i = 0; i < dt.Columns.Count; i++) { PropertyInfo info = plist.Find(p => p.Name == dt.Columns[i].ColumnName); if (info != null) { try { if (!Convert.IsDBNull(item[i])) { object v = null; if (info.PropertyType.ToString().Contains("System.Nullable")) { v = Convert.ChangeType(item[i], Nullable.GetUnderlyingType(info.PropertyType)); } else { v = Convert.ChangeType(item[i], info.PropertyType); } info.SetValue(s, v, null); } } catch (Exception ex) { throw new Exception("字段[" + info.Name + "]转换出错," + ex.Message); } } } list.Add(s); } return list; } /// /// List转换成DataTable /// /// /// public static DataTable ListToDataTable(IList list) { System.Data.DataTable result = new System.Data.DataTable(); if (list.Count > 0) { PropertyInfo[] propertys = list[0].GetType().GetProperties(); foreach (PropertyInfo pi in propertys) { //获取类型 Type colType = pi.PropertyType; //当类型为Nullable<>时 if ((colType.IsGenericType) && (colType.GetGenericTypeDefinition() == typeof(Nullable<>))) { colType = colType.GetGenericArguments()[0]; } result.Columns.Add(pi.Name, colType); } for (int i = 0; i < list.Count; i++) { ArrayList tempList = new ArrayList(); foreach (PropertyInfo pi in propertys) { object obj = pi.GetValue(list[i], null); tempList.Add(obj); } object[] array = tempList.ToArray(); result.LoadDataRow(array, true); } } return result; } /// /// 表拆分 /// /// /// /// public static List DataTableSplite(DataTable dt, int modcounts) { int counts = dt.Rows.Count / modcounts; /// 取整数个数 List list = new List(); int index = 0; for (int i = 0; i < counts + 1; i++) { list.Add(dt.AsEnumerable().Skip(index * modcounts).Take(modcounts).CopyToDataTable()); index++; } return list; } /// /// Ping测试 /// /// /// public static bool BoolPing(string ip) { var pingbool = true; try { var ping = new Ping(); var replay = ping.Send(ip, 1000); if (replay.Status != IPStatus.Success) { pingbool = false; } return pingbool; } catch (Exception ex) { LogHelper.WriteErrorLog("Ping操作异常!", ex); return false; } } /// /// 生成条码 /// /// /// public static string NumFormat(int a) { string num = ""; if (a <= 9) { num = "000" + a.ToString(); } if (a > 9 && a <= 99) { num = "00" + a.ToString(); } if (a > 99 && a <= 999) { num = "0" + a.ToString(); } if (a > 999) { num = a.ToString(); } return num; } /// /// 字节数组转16进制字符串数组 /// /// /// public static string[] ByteArrayToHexStrArray(byte[] bytes) { string[] sHexStrArray = null; if (bytes?.Length > 0) { sHexStrArray = new string[bytes.Length]; for (int i = 0; i < bytes.Length; i++) { sHexStrArray[i] = bytes[i].ToString("X2"); } } return sHexStrArray; } /// /// 字节数组转16进制字符串 /// /// /// public static (bool isok, string msg) ByteArrayToHexStr(byte[] bytes, string separator = "") { try { string returnStr = ""; if (bytes?.Length > 0) { foreach (byte byteItem in bytes) { returnStr += byteItem.ToString("X2") + separator; } } return (true, returnStr.Trim()); } catch (Exception ex) { var msg = ex == null ? "操作异常" : ex.Message; return (false, ""); } } /// /// 字符串转16进制字符 /// /// 字符串 /// 编码格式 /// public static string StringToHexString(string _str, Encoding encode) { //去掉空格 _str = _str.Replace(" ", ""); //将字符串转换成字节数组。 byte[] buffer = encode.GetBytes(_str); //定义一个string类型的变量,用于存储转换后的值。 string result = string.Empty; for (int i = 0; i < buffer.Length; i++) { //将每一个字节数组转换成16进制的字符串,以空格相隔开。 result += Convert.ToString(buffer[i], 16) + " "; } return result; } /// /// 16进制字符转字符串 /// /// 16进制字符 /// 编码格式 /// public static string HexStringToString(string hex, Encoding encode) { byte[] buffer = new byte[hex.Length / 2]; string result = string.Empty; for (int i = 0; i < hex.Length / 2; i++) { result = hex.Substring(i * 2, 2); buffer[i] = Convert.ToByte(result, 16); } //返回指定编码格式的字符串 return encode.GetString(buffer); } /// /// 获取通讯协议的CRC(校验和)值 /// /// /// public static string ProtocolCRC(string strHex) { string[] hexArr = strHex.Split(' '); int totalNum = 0; for (int i = 0; i < hexArr.Length; i++) { totalNum += Convert.ToInt32(hexArr[i], 16); } int low = totalNum & 0xff;//低8位 //int high = (value >> 8) & 0xff;//高8位 var CRCVal = NumberToHexByteArray(low, "X2"); return $"{strHex} {CRCVal}"; } /// /// 十进制转十六进制字符串 /// /// /// /// public static string NumberToHexByteArray(int data, string strHEx = "X4") { var str = string.Empty; int count = 2;//每两个字符进行分割 var hexStr = data.ToString(strHEx); int length = (int)Math.Ceiling((double)hexStr.Length / count); for (int i = 0; i < length; i++) { int start = count * i; if (hexStr.Length <= start) { break; } if (hexStr.Length < start + count) { str += hexStr.Substring(start) + " "; } else { str += hexStr.Substring(start, count) + " "; } } return str; } /// /// 根据key设置AppConfig值 /// /// /// public static (bool isSuccess, string msg) WriteValueByKey(string key, string val) { try { Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None); if (config.AppSettings.Settings[key] == null) { return (false, $"AppConfigHelper.WriteValueByKey()入参key={key}不存在!"); } config.AppSettings.Settings[key].Value = val; config.AppSettings.SectionInformation.ForceSave = true; config.Save(ConfigurationSaveMode.Modified); ConfigurationManager.RefreshSection("appSettings"); return (true, "操作成功"); } catch (Exception ex) { return (false, $"AppConfigHelper.WriteValueByKey()操作失败{ex.StackTrace},Key={key},Val={val}"); } } } }