• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    公众号

C#最牛逼的Utility工具类

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

完整代码:

 

using System;
using System.Collections.Specialized;
using System.IO;
using System.Net;
using System.Text;
using System.Text.RegularExpressions;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
using System.Security.Cryptography.X509Certificates;
using System.Net.Security;
using System.Reflection;
using System.ComponentModel;

namespace DBUtility
{
   public class DButility
    {
        private static Random ran = new Random();
        private static readonly int TIMEOUT = 5000;
        #region DBNull类型转换
        public static long ToInt64(object value)
        {
            return (Convert.IsDBNull(value)) ? 0 : Convert.ToInt64(value);
        }

        public static int ToInt32(object value)
        {
            return (Convert.IsDBNull(value)) ? 0 : Convert.ToInt32(value);
        }

        public static short ToInt16(object value)
        {
            return (Convert.IsDBNull(value)) ? (short)0 : Convert.ToInt16(value);
        }

        public static string ToString(object value)
        {
            return value.ToString();
        }

        public static decimal ToDecimal(object value)
        {
            return (Convert.IsDBNull(value)) ? 0 : Convert.ToDecimal(value);
        }

        public static DateTime ToDateTime(object value)
        {
            return (Convert.IsDBNull(value)) ? DateTime.MinValue : Convert.ToDateTime(value);
        }
        #endregion

        #region AES 加密/解密
        /// <summary>
        ///  AES 加密
        /// </summary>
        /// <param name="str">明文(待加密)</param>
        /// <param name="key">密文</param>
        /// <returns></returns>
        public static string AesEncryptToHex(string str, string key)
        {
            if (string.IsNullOrEmpty(str)) return null;
            Byte[] toEncryptArray = Encoding.UTF8.GetBytes(str);   //命名空间: using System.Text;

            System.Security.Cryptography.RijndaelManaged rm = new System.Security.Cryptography.RijndaelManaged
            {
                Key = Encoding.UTF8.GetBytes(key),
                Mode = System.Security.Cryptography.CipherMode.ECB,
                Padding = System.Security.Cryptography.PaddingMode.PKCS7
            };

            System.Security.Cryptography.ICryptoTransform cTransform = rm.CreateEncryptor();
            Byte[] resultArray = cTransform.TransformFinalBlock(toEncryptArray, 0, toEncryptArray.Length);

            var hex = BitConverter.ToString(resultArray, 0).Replace("-", string.Empty).ToLower();
            return hex;
        }

        /// <summary>
        ///  AES 解密
        /// </summary>
        /// <param name="str">明文(待解密)</param>
        /// <param name="key">密文</param>
        /// <returns></returns>
        public static string AesDecryptFromHex(string str, string key)
        {
            if (string.IsNullOrEmpty(str)) return null;
            var toEncryptArray = new byte[str.Length / 2];
            for (var x = 0; x < toEncryptArray.Length; x++)
            {
                var i = Convert.ToInt32(str.Substring(x * 2, 2), 16);
                toEncryptArray[x] = (byte)i;
            }

            //Byte[] toEncryptArray = Convert.FromBase64String(str);

            System.Security.Cryptography.RijndaelManaged rm = new System.Security.Cryptography.RijndaelManaged
            {
                Key = Encoding.UTF8.GetBytes(key),
                Mode = System.Security.Cryptography.CipherMode.ECB,
                Padding = System.Security.Cryptography.PaddingMode.PKCS7
            };

            System.Security.Cryptography.ICryptoTransform cTransform = rm.CreateDecryptor();
            Byte[] resultArray = cTransform.TransformFinalBlock(toEncryptArray, 0, toEncryptArray.Length);

            return Encoding.UTF8.GetString(resultArray);
        }
        #endregion

        #region 获取时间戳,取随机数
        /// <summary>
        /// 获取时间戳
        /// </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);
        }

        /// <summary>
        /// 取随机数
        /// </summary>
        /// <param name="min"></param>
        /// <param name="max"></param>
        /// <returns></returns>
        public static int GetRandom(int min, int max)
        {
            return ran.Next(min, max);
        }

        /// <summary>
        /// 获取当前本地时间戳
        /// </summary>
        /// <returns></returns>
        public static long GetCurrentTimeUnix()
        {
            TimeSpan cha = (DateTime.Now - TimeZone.CurrentTimeZone.ToLocalTime(new System.DateTime(1970, 1, 1)));
            long t = (long)cha.TotalSeconds;
            return t;
        }

        /// <summary>
        /// 时间戳转换为本地时间对象
        /// </summary>
        /// <returns></returns>
        public static DateTime GetUnixDateTime(long unix)
        {
            //long unix = 1500863191;
            DateTime dtStart = TimeZone.CurrentTimeZone.ToLocalTime(new DateTime(1970, 1, 1));
            DateTime newTime = dtStart.AddSeconds(unix);
            return newTime;
        }

        /// <summary>
        /// Unicode转字符串
        /// </summary>
        /// <param name="source">经过Unicode编码的字符串</param>
        /// <returns>正常字符串</returns>
        public static string UnicodeToString(string source)
        {
            return new Regex(@"\\u([0-9A-F]{4})", RegexOptions.IgnoreCase | RegexOptions.Compiled).Replace(
                         source, x => string.Empty + Convert.ToChar(Convert.ToUInt16(x.Result("$1"), 16)));
        }

        /// <summary>
        /// Stream流转化为字符串
        /// </summary>
        /// <returns></returns>
        public static string StreamToString(Stream stream)
        {
            if (stream == null || stream.Length == 0)
            {
                return string.Empty;
            }
            StreamReader sr = new StreamReader(stream);
            return sr.ReadToEnd();
        }

        /// <summary>
        /// RequestForm转换成String, key=value格式
        /// </summary>
        /// <returns></returns>
        public static string RequestFormToString(NameValueCollection form)
        {
            if (form == null)
            {
                return null;
            }

            string strTemp = string.Empty;

            String[] requestItem = form.AllKeys;
            for (int i = 0; i < requestItem.Length; i++)
            {
                strTemp += requestItem[i] + "=" + form[requestItem[i]] + "&";
            }

            strTemp = strTemp.TrimEnd('&');
            return strTemp;
        }
        #endregion

        #region HttpUtils

        public static string HttpPost(string Url, string mobiles, string content)
        {
            string postData = string.Format("mobiles={0}&content={1}", mobiles, content);

            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(Url);
            System.Net.ServicePointManager.DefaultConnectionLimit = 200;
            request.Method = "POST";
            request.KeepAlive = false;
            request.ContentType = "application/x-www-form-urlencoded";
            request.ContentLength = Encoding.UTF8.GetByteCount(postData);
            Stream myRequestStream = request.GetRequestStream();
            StreamWriter myStreamWriter = new StreamWriter(myRequestStream, Encoding.GetEncoding("gb2312"));
            myStreamWriter.Write(postData, 0, postData.Length);
            myStreamWriter.Close();
            HttpWebResponse response = (HttpWebResponse)request.GetResponse();

            Stream myResponseStream = response.GetResponseStream();
            StreamReader myStreamReader = new StreamReader(myResponseStream, Encoding.GetEncoding("utf-8"));
            string retString = myStreamReader.ReadToEnd();
            myStreamReader.Close();

            myResponseStream.Close();

            response = null;
            request = null;
            return retString;
        }



        /// <summary>  
        /// 指定Post地址使用Get 方式获取全部字符串  
        /// </summary>  
        /// <param name="url">请求后台地址</param>  
        /// <returns></returns>  
        public static string Post(string url, Dictionary<string, string> dic)
        {
            string result = "";
            HttpWebRequest req = (HttpWebRequest)WebRequest.Create(url);
            string mobiles = dic["mobiles"];
            string content = dic["content"];
            req.Method = "POST";
            req.ContentType = "application/x-www-form-urlencoded";
            #region 添加Post 参数
            StringBuilder builder = new StringBuilder();
            int i = 0;
            foreach (var item in dic)
            {
                if (i > 0)
                    builder.Append("&");
                builder.AppendFormat("{0}={1}", item.Key, item.Value);
                i++;
            }
            byte[] data = Encoding.UTF8.GetBytes(builder.ToString());
            req.ContentLength = data.Length;
            using (Stream reqStream = req.GetRequestStream())
            {
                reqStream.Write(data, 0, data.Length);
                reqStream.Close();
            }
            #endregion
            HttpWebResponse resp = (HttpWebResponse)req.GetResponse();
            Stream stream = resp.GetResponseStream();
            //获取响应内容  
            using (StreamReader reader = new StreamReader(stream, Encoding.UTF8))
            {
                result = reader.ReadToEnd();
            }
            return result;
        }

        /// <summary>  
        /// 指定地址使用Get 方式获取全部字符串  
        /// </summary>  
        /// <param name="url">请求后台地址</param>  
        /// <returns></returns>  
        public static string Get(string url, Dictionary<string, string> dic)
        {
            string result = "";
            HttpWebRequest req = (HttpWebRequest)WebRequest.Create(url);
            string uname = dic["username"];
            string pwd = dic["password"];
            req.Method = "GET";
            req.ContentType = "application/x-www-form-urlencoded";
            HttpWebResponse resp = (HttpWebResponse)req.GetResponse();
            Stream stream = resp.GetResponseStream();
            //获取响应内容  
            using (StreamReader reader = new StreamReader(stream, Encoding.UTF8))
            {
                result = reader.ReadToEnd();
            }
            return result;
        }

        public static string PostSend(string url, string param)
        {
            return PostSend(url, "UTF-8", param);
        }

        public static string PostSend(string url, string encoding, string param, string contentType = "application/x-www-form-urlencoded")
        {
            try
            {
                byte[] postData = Encoding.UTF8.GetBytes(param);

                HttpWebRequest request = WebRequest.Create(url) as HttpWebRequest;
                Encoding myEncoding = Encoding.UTF8;
                request.Method = "POST";
                request.KeepAlive = false;
                request.AllowAutoRedirect = true;
                request.ContentType = contentType;
                request.UserAgent = "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1; .NET CLR 2.0.50727; .NET CLR  3.0.04506.648; .NET CLR 3.5.21022; .NET CLR 3.0.4506.2152; .NET CLR 3.5.30729)";
                request.ContentLength = postData.Length;
                request.Timeout = TIMEOUT;

                System.IO.Stream outputStream = request.GetRequestStream();
                outputStream.Write(postData, 0, postData.Length);
                outputStream.Close();

                HttpWebResponse response = request.GetResponse() as HttpWebResponse;

                Stream responseStream = response.GetResponseStream();

                StreamReader reader = new System.IO.StreamReader(responseStream, Encoding.GetEncoding("UTF-8"));

                string retVal = reader.ReadToEnd();

                reader.Close();

                return retVal;
            }
            catch (Exception ex)
            {
                LogHelper.Error("PostSend [url:]" + url + " [params:]" + param + " [error:]" + ex.Message);
                return ex.Message;
            }
        }

        public static string PostSendWithCert(string url, string param)
        {
            return PostSendWithCert(url, "UTF-8", param);
        }

        public static string PostSendWithCert(string url, string encoding, string param, string contentType = "application/x-www-form-urlencoded")
        {
            try
            {
                string cert = System.Configuration.ConfigurationManager.AppSettings["CertPath"];
                string password = System.Configuration.ConfigurationManager.AppSettings["xcxMchId"];
                ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback(CheckValidationResult);
                X509Certificate2 cer = new X509Certificate2(cert, password, X509KeyStorageFlags.PersistKeySet | X509KeyStorageFlags.MachineKeySet);

                byte[] postData = Encoding.UTF8.GetBytes(param);

                HttpWebRequest request = WebRequest.Create(url) as HttpWebRequest;
                Encoding myEncoding = Encoding.UTF8;
                request.ClientCertificates.Add(cer);
                request.Method = "POST";
                request.KeepAlive = false;
                request.AllowAutoRedirect = true;
                request.ContentType = contentType;
                request.UserAgent = "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1; .NET CLR 2.0.50727; .NET CLR  3.0.04506.648; .NET CLR 3.5.21022; .NET CLR 3.0.4506.2152; .NET CLR 3.5.30729)";
                request.ContentLength = postData.Length;
                request.Timeout = TIMEOUT;

                System.IO.Stream outputStream = request.GetRequestStream();
                outputStream.Write(postData, 0, postData.Length);
                outputStream.Close();

                HttpWebResponse response = request.GetResponse() as HttpWebResponse;

                Stream responseStream = response.GetResponseStream();

                StreamReader reader = new System.IO.StreamReader(responseStream, Encoding.GetEncoding("UTF-8"));

                string retVal = reader.ReadToEnd();

                reader.Close();

                return retVal;
            }
            catch (Exception ex)
            {
                LogHelper.Error("PostSend [url:]" + url + " [params:]" + param + " [error:]" + ex.Message);
                return ex.Message;
            }
        }

        /// <summary>
        /// 发请求获取图片到本地路径
        /// </summary>
        /// <param name="url"></param>
        /// <param name="param"></param>
        /// <param name="pathName"></param>
        /// <param name="contentType"></param>
        public static void PostSaveToFile(string url, string param, string pathName, string contentType = "application/x-www-form-urlencoded")
        {
            try
            {
                byte[] postData = Encoding.UTF8.GetBytes(param);

                HttpWebRequest request = WebRequest.Create(url) as HttpWebRequest;
                Encoding myEncoding = Encoding.UTF8;
                request.Method = "POST";
                request.KeepAlive = false;
                request.AllowAutoRedirect = true;
                request.ContentType = contentType;
                request.UserAgent = "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1; .NET CLR 2.0.50727; .NET CLR  3.0.04506.648; .NET CLR 3.5.21022; .NET CLR 3.0.4506.2152; .NET CLR 3.5.30729)";
                request.ContentLength = postData.Length;
                request.Timeout = TIMEOUT;

                System.IO.Stream outputStream = request.GetRequestStream();
                outputStream.Write(postData, 0, postData.Length);
                outputStream.Close();

                HttpWebResponse response = request.GetResponse() as HttpWebResponse;

                Stream responseStream = response.GetResponseStream();

                System.Drawing.Image.FromStream(responseStream).Save(pathName);
            }
            catch (Exception ex)
            {
                LogHelper.Error("PostSend [url:]" + url + " [params:]" + param + " [error:]" + ex.Message);
            }
        }

        public static string HttpGet(string Url, string postDataStr = "")
        {
            try
            {
                HttpWebRequest request = (HttpWebRequest)WebRequest.Create(Url + (postDataStr == "" ? "" : "?") + postDataStr);
                // https
                if (Url.StartsWith("https", StringComparison.OrdinalIgnoreCase))
                {
                    ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback(CheckValidationResult);
                    request.ProtocolVersion = HttpVersion.Version10;
                }

                request.Method = "GET";
                request.ContentType = "text/html;charset=UTF-8";
                request.Timeout = 3000;

                HttpWebResponse response = (HttpWebResponse)request.GetResponse();
                Stream myResponseStream = response.GetResponseStream();
                StreamReader myStreamReader = new StreamReader(myResponseStream, Encoding.GetEncoding("utf-8"));
                string retString = myStreamReader.ReadToEnd();
                myStreamReader.Close();
                myResponseStream.Close();

                return retString;
            }
            catch (Exception e)
            {
                Console.WriteLine(e.Message);
                return null;
            }
        }

        private static bool CheckValidationResult(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors errors)
        {
            return true; //总是接受  
        }
        #endregion

        #region MD5加密

        /// <summary>
        /// 
        /// </summary>
        /// <param name="sDataIn"></param>
        /// <param name="move">给空即可</param>
        /// <returns></returns>
        public static string GetMD532(string sDataIn, string move)
        {
            System.Security.Cryptography.MD5CryptoServiceProvider md5 = new System.Security.Cryptography.MD5CryptoServiceProvider();
            byte[] bytValue, bytHash;
            bytValue = System.Text.Encoding.UTF8.GetBytes(move + sDataIn);
            bytHash = md5.ComputeHash(bytValue);
            md5.Clear();
            string sTemp = "";
            for (int i = 0; i < bytHash.Length; i++)
            {
                sTemp += bytHash[i].ToString("x").PadLeft(2, '0');
            }
            return sTemp;
        }

        public static string GetMD516(string ConvertString)
        {
            System.Security.Cryptography.MD5CryptoServiceProvider md5 = new System.Security.Cryptography.MD5CryptoServiceProvider();
            string t2 = BitConverter.ToString(md5.ComputeHash(UTF8Encoding.Default.GetBytes(ConvertString)), 4, 8);
            t2 = t2.Replace("-", "");

            t2 = t2.ToLower();

            return t2;
        }
        #endregion
    }
    #region log4net 日志类
    public class LogHelper
    {
        //在 <configuration></configuration>里面添加下面配置

        //      <configSections>
        //  <section name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler,log4net"/>
        //</configSections>

        //        <log4net>
        //  <logger name="logerror">
        //    <level value="ERROR"/>
        //    <appender-ref ref="ErrorAppender"/>
        //  </logger>
        //  <logger name="loginfo">
        //    <level value="INFO"/>
        //    <appender-ref ref="InfoAppender"/>
         
                       
                    
                    

鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
C#RichTextBox滚动条滚动到最后一行发布时间:2022-07-14
下一篇:
C#中使用OracleTransaction发布时间:2022-07-14
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap