c# 常用 Common

        /// <summary>
        ///  md5加密字符串
        /// </summary>
        /// <param name="message"></param>
        /// <returns></returns>
        public static String ToMD5(this String message)
        {
            MD5 md5 = new MD5CryptoServiceProvider();
            byte[] result = Encoding.UTF8.GetBytes(message);
            byte[] outStr = md5.ComputeHash(result);
            string md5string = BitConverter.ToString(outStr).Replace("-", "");
            return md5string;
        }
        /// <summary>
        /// 按字节数截取字符串的方法
        /// </summary>
        /// <param name="source">要截取的字符串(可空)</param>
        /// <param name="NumberOfBytes">要截取的字节数</param>
        /// <param name="encoding">System.Text.Encoding</param>
        /// <param name="suffix">结果字符串的后缀(超出部分显示为该后缀)</param>
        /// <returns></returns>
        public static string SubStringByBytes(this string source, int NumberOfBytes, System.Text.Encoding encoding, string suffix = "")
        {
            if (string.IsNullOrWhiteSpace(source) || source.Length == 0)
                return source;

            if (encoding.GetBytes(source).Length <= NumberOfBytes)
                return source;

            long tempLen = 0;
            StringBuilder sb = new StringBuilder();
            foreach (var c in source)
            {
                Char[] _charArr = new Char[] { c };
                byte[] _charBytes = encoding.GetBytes(_charArr);
                if ((tempLen + _charBytes.Length) > NumberOfBytes)
                {
                    if (!string.IsNullOrWhiteSpace(suffix))
                        sb.Append(suffix);
                    break;
                }
                else
                {
                    tempLen += _charBytes.Length;
                    sb.Append(encoding.GetString(_charBytes));
                }
            }
            return sb.ToString();
        }
        /// <summary>
        /// 复制一个对象
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="info"></param>
        /// <returns></returns>
        public static T Copy<T>(T info) where T : new()
        {
            string json = JsonHelper.SerializeObject(info);
            return JsonConvert.DeserializeObject<T>(json);
        }

 

        /// <summary>
        /// 对象转Json字符串
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="data"></param>
        /// <returns></returns>
        public static string ToJson<T>(T data) where T : new()
        {
            return JsonHelper.SerializeObject(data);
        }

 

c# 常用 Common

上一篇:windows10 添加局域网打印机


下一篇:C# 反射的委托创建器