| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383 |
- using System;
- using System.Collections.Generic;
- using System.IO;
- using System.Linq.Expressions;
- using System.Runtime.Serialization;
- using System.Runtime.Serialization.Formatters.Binary;
- using System.Security.Cryptography;
- using System.Text;
- namespace ReleaseHelper.Utils
- {
- public static class Functions
- {
- //static byte[] Encrypt(string input)
- //{
- // StringBuilder sb = new StringBuilder();
- // int i = 0;
- // int offset = Variables.Const.KEY[0];
- // foreach (char c in input)
- // {
- // var c2 = Convert.ToChar(c + Variables.Const.KEY[i++] + offset);
- // sb.Append(c2);
- // }
- // return Encoding.UTF8.GetBytes(sb.ToString());
- //}
- //static string Decrypt(byte[] input)
- //{
- // StringBuilder sb = new StringBuilder();
- // int i = 0;
- // int offset = Variables.Const.KEY[0];
- // string s = Encoding.UTF8.GetString(input);
- // foreach (char b in s)
- // {
- // sb.Append(Convert.ToChar(b - offset - Variables.Const.KEY[i++]));
- // }
- // return sb.ToString();
- //}
- //public static string LoadUserPW(string n, byte[] pwd)
- //{
- // return Decrypt(pwd).Substring($"{n}_".Length);
- //}
- //public static byte[] DumpUserPW(string n, string pwd)
- //{
- // return Encrypt($"{n}_{pwd}");
- //}
- /// <summary>
- /// 字符串生成MD5
- /// </summary>
- /// <param name="s"></param>
- /// <returns></returns>
- public static string GenMd5(string s)
- {
- //就是比string往后一直加要好的优化容器
- StringBuilder sb = new StringBuilder();
- using (MD5CryptoServiceProvider md5 = new MD5CryptoServiceProvider())
- {
- //将输入字符串转换为字节数组并计算哈希。
- byte[] data = md5.ComputeHash(Encoding.UTF8.GetBytes(s));
- //X为 十六进制 X都是大写 x都为小写
- //2为 每次都是两位数
- //假设有两个数10和26,正常情况十六进制显示0xA、0x1A,这样看起来不整齐,为了好看,可以指定"X2",这样显示出来就是:0x0A、0x1A。
- //遍历哈希数据的每个字节
- //并将每个字符串格式化为十六进制字符串。
- int length = data.Length;
- for (int i = 0; i < length; i++)
- {
- sb.Append(data[i].ToString("X2"));
- }
- }
- return sb.ToString();
- }
- /// <summary>
- /// 获取文件的MD5码
- /// </summary>
- /// <param name="fileName">传入的文件名(含路径及后缀名)</param>
- /// <returns></returns>
- /// <exception cref="Exception"></exception>
- public static string GenMd5HashFromFile(string fileName)
- {
- try
- {
- StringBuilder sb = new StringBuilder();
- using (MD5 md5 = new MD5CryptoServiceProvider())
- using (FileStream file = new FileStream(fileName, FileMode.Open))
- {
- byte[] retVal = md5.ComputeHash(file);
- //file.Close();
- for (int i = 0; i < retVal.Length; i++)
- {
- sb.Append(retVal[i].ToString("X2"));
- }
- }
- return sb.ToString();
- }
- catch (Exception ex)
- {
- throw new Exception("GetMD5HashFromFile() fail,error:" + ex.Message);
- }
- }
- /// <summary>
- /// 生成UUID
- /// </summary>
- /// <returns></returns>
- public static string GenUUID()
- {
- return Guid.NewGuid().ToString("N");
- }
- /// <summary>
- /// 深复制对象
- /// </summary>
- /// <typeparam name="T"></typeparam>
- /// <param name="source"></param>
- /// <returns></returns>
- /// <exception cref="ArgumentException"></exception>
- public static T Clone<T>(T source)
- {
- if (!typeof(T).IsSerializable)
- {
- throw new ArgumentException("The type must be serializable.", "source");
- }
- // Don't serialize a null object, simply return the default for that object
- if (source == null)
- {
- return default;
- }
- IFormatter formatter = new BinaryFormatter();
- //Stream stream = new MemoryStream();
- using (Stream stream = new MemoryStream())
- {
- formatter.Serialize(stream, source);
- stream.Seek(0, SeekOrigin.Begin);
- return (T)formatter.Deserialize(stream);
- }
- }
- /// <summary>
- /// 生成任务id
- /// </summary>
- /// <param name="testId"></param>
- /// <returns></returns>
- public static string GenTaskId(int testId)
- {
- return GenTaskId(testId, Utils.Functions.GenUUID());
- }
- /// <summary>
- /// 生成任务id
- /// </summary>
- /// <param name="testId"></param>
- /// <param name="uuid"></param>
- /// <returns></returns>
- public static string GenTaskId(int testId, string uuid)
- {
- return $"{testId}_{uuid}";
- }
- /// <summary>
- /// 返回字符串右侧指定数量的字符串
- /// </summary>
- /// <param name="txt"></param>
- /// <param name="length"></param>
- /// <returns></returns>
- public static string RString(string txt, int length)
- {
- string res = string.Empty;
- if (!string.IsNullOrEmpty(txt))
- {
- res = length > txt.Length ? txt : txt.Substring(txt.Length - length);
- }
- return res;
- }
- /// <summary>
- /// 复制对象
- /// </summary>
- /// <typeparam name="TIn"></typeparam>
- /// <typeparam name="TOut"></typeparam>
- public static class CopyTo<TIn, TOut>
- {
- private static readonly Func<TIn, TOut> cache = GetFunc();
- private static Func<TIn, TOut> GetFunc()
- {
- ParameterExpression parameterExpression = Expression.Parameter(typeof(TIn), "p");
- List<MemberBinding> memberBindingList = new List<MemberBinding>();
- foreach (var item in typeof(TOut).GetProperties())
- {
- if (!item.CanWrite)
- continue;
- MemberExpression property = Expression.Property(parameterExpression, typeof(TIn).GetProperty(item.Name));
- MemberBinding memberBinding = Expression.Bind(item, property);
- memberBindingList.Add(memberBinding);
- }
- MemberInitExpression memberInitExpression = Expression.MemberInit(Expression.New(typeof(TOut)), memberBindingList.ToArray());
- Expression<Func<TIn, TOut>> lambda = Expression.Lambda<Func<TIn, TOut>>(memberInitExpression, new ParameterExpression[] { parameterExpression });
- return lambda.Compile();
- }
- public static TOut Trans(TIn tIn)
- {
- return cache(tIn);
- }
- }
- /// <summary>
- /// 获取时间戳 13位
- /// </summary>
- /// <returns></returns>
- public static long GetTimeStamp()
- {
- TimeSpan ts = DateTime.UtcNow - new DateTime(1970, 1, 1, 0, 0, 0, 0);
- return Convert.ToInt64(ts.TotalSeconds * 1000);
- }
- /// <summary>
- /// 将时间戳转换为日期类型,并格式化
- /// </summary>
- /// <param name="longDateTime"></param>
- /// <returns></returns>
- public static string LongDateTimeToDateTimeString(string longDateTime)
- {
- //用来格式化long类型时间的,声明的变量
- long unixDate;
- DateTime start;
- DateTime date;
- //ENd
- unixDate = long.Parse(longDateTime);
- start = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc);
- date = start.AddMilliseconds(unixDate).ToLocalTime();
- return date.ToString("yyyy-MM-dd HH:mm:ss");
- }
- /// <summary>
- /// 获取制定路径文件的md5值
- /// </summary>
- /// <param name="filename"></param>
- /// <returns></returns>
- public static string FileMd5(string filename)
- {
- string res = "";
- try
- {
- using (FileStream file = new FileStream(filename, FileMode.Open))
- using (MD5 md5 = new MD5CryptoServiceProvider())
- {
- byte[] retVal = md5.ComputeHash(file);
- StringBuilder sb = new StringBuilder();
- for (int i = 0; i < retVal.Length; i++)
- {
- sb.Append(retVal[i].ToString("x2"));
- }
- res = sb.ToString();
- }
- }
- catch
- {
- }
- return res;
- }
- ///// <summary>
- ///// 生成上传文件对象的名称
- ///// </summary>
- ///// <param name="subjectId">科目id</param>
- ///// <param name="filename">文件名</param>
- ///// <returns></returns>
- //public static string GenUploadImageName(int subjectId, string filename)
- //{
- // string fileMd5 = FileMd5(filename), objectName = string.Empty;
- // if (!string.IsNullOrEmpty(fileMd5))
- // {
- // // 保存的文件名
- // objectName = $"images/marking/{Variables.Variables.SubjectIdCode[subjectId]}/{fileMd5.Substring(0, 4)}/{fileMd5}{Path.GetExtension(filename)}";
- // }
- // return objectName;
- //}
- ///// <summary>
- ///// 获得已使用的物理内存的大小,单位 (Byte),如果获取失败,返回 -1.
- ///// </summary>
- ///// <returns></returns>
- //public static double GetTotalPhysicalMemory(FileSizeUnit targetUnit = FileSizeUnit.MB)
- //{
- // long capacity = 0;
- // try
- // {
- // foreach (ManagementObject mo1 in new ManagementClass("Win32_PhysicalMemory").GetInstances().Cast<ManagementObject>())
- // {
- // capacity += long.Parse(mo1.Properties["Capacity"].Value.ToString());
- // }
- // }
- // catch (Exception ex)
- // {
- // capacity = -1;
- // Console.WriteLine(ex.Message);
- // }
- // return ToFileFormat(capacity, targetUnit);
- //}
- ///// <summary>
- ///// 获得已使用的物理内存的大小,单位 (Byte),如果获取失败,返回 -1.
- ///// </summary>
- ///// <returns></returns>
- //public static double GetAvailablePhysicalMemory(FileSizeUnit targetUnit = FileSizeUnit.MB)
- //{
- // long capacity = 0;
- // try
- // {
- // foreach (ManagementObject mo1 in new ManagementClass("Win32_PerfFormattedData_PerfOS_Memory").GetInstances().Cast<ManagementObject>())
- // {
- // capacity += long.Parse(mo1.Properties["AvailableBytes"].Value.ToString());
- // }
- // }
- // catch (Exception ex)
- // {
- // capacity = -1;
- // Console.WriteLine(ex.Message);
- // }
- // return ToFileFormat(capacity, targetUnit);
- //}
- ///// <summary>
- ///// 根据指定的文件大小单位,对输入的文件大小(字节表示)进行转换。
- ///// </summary>
- ///// <param name="filesize">文件文件大小,单位为字节。</param>
- ///// <param name="targetUnit">目标单位。</param>
- ///// <returns></returns>
- //private static double ToFileFormat(long filesize, FileSizeUnit targetUnit = FileSizeUnit.MB)
- //{
- // double size;
- // switch (targetUnit)
- // {
- // case FileSizeUnit.KB: size = filesize / 1024.0; break;
- // case FileSizeUnit.MB: size = filesize / 1024.0 / 1024; break;
- // case FileSizeUnit.GB: size = filesize / 1024.0 / 1024 / 1024; break;
- // case FileSizeUnit.TB: size = filesize / 1024.0 / 1024 / 1024 / 1024; break;
- // case FileSizeUnit.PB: size = filesize / 1024.0 / 1024 / 1024 / 1024 / 1024; break;
- // default: size = filesize; break;
- // }
- // return size;
- //}
- ///// <summary>
- ///// 文件大小单位,包括从B至PB共六个单位。
- ///// </summary>
- //public enum FileSizeUnit
- //{
- // B,
- // KB,
- // MB,
- // GB,
- // TB,
- // PB
- //}
- }
- }
|