| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353 |
- 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;
- using System.Threading;
- namespace DaJiaoYan.Utils
- {
- internal class Functions
- {
- private static readonly Queue<string> Pool = new Queue<string>();
- private static readonly object _UUIDLocker = new object();
- /// <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);
- }
- }
- private static void UUIDInit()
- {
- lock (_UUIDLocker)
- {
- for (int i = 0; i < 10000; i++)
- {
- Pool.Enqueue(Guid.NewGuid().ToString("N"));
- Thread.Sleep(1);
- }
- }
- }
- /// <summary>
- /// UUID生成程序
- /// </summary>
- public static void UUIDBackgroundFunc()
- {
- new Thread(() =>
- {
- while (true)
- {
- if (Pool.Count < 5000)
- {
- UUIDInit();
- }
- Thread.Sleep(1000);
- }
- })
- {
- IsBackground = true
- }.Start();
- }
- /// <summary>
- /// 生成UUID
- /// </summary>
- /// <returns></returns>
- public static string GenUUID()
- {
- //if (Pool.Count <= 100)
- //{
- // UUIDInit();
- //}
- return Pool.Dequeue();
- }
- /// <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>
- /// 返回字符串右侧指定数量的字符串
- /// </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="testId"></param>
- /// <param name="campusId"></param>
- /// <param name="filename"></param>
- /// <returns></returns>
- public static string GenUploadOriginImageName(int testId, int campusId, string filename, string batchId = null)
- {
- string res;
- if (string.IsNullOrEmpty(batchId))
- {
- res = $"origin/{testId}/{campusId}/{Path.GetFileName(filename)}";
- }
- else
- {
- res = $"origin/{testId}/{campusId}/{batchId}/{Path.GetFileName(filename)}";
- }
- return res;
- }
- public static long GetHardDiskSpace(string str_HardDiskName)
- {
- long totalSize = 0;
- str_HardDiskName += ":\\";
- System.IO.DriveInfo[] drives = System.IO.DriveInfo.GetDrives();
- foreach (System.IO.DriveInfo drive in drives)
- {
- if (string.Equals(drive.Name, str_HardDiskName, StringComparison.OrdinalIgnoreCase))
- {
- totalSize = drive.TotalFreeSpace;
- }
- }
- return totalSize;
- }
- public static string GetHardDiskFreeSpace(string str_HardDiskFreeSpace, FileSizeUnit targetUnit = FileSizeUnit.MB)
- {
- long totalSize = GetHardDiskSpace(str_HardDiskFreeSpace);
- return Math.Floor(ToFileFormat(totalSize, targetUnit)).ToString() + Enum.GetName(typeof(FileSizeUnit), 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
- }
- }
- }
|