共用方法整理

Posted hugeboke

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了共用方法整理相关的知识,希望对你有一定的参考价值。

 #region 获取文件后缀
        public static string GetExtendName(string filename)
        
            if (!string.IsNullOrEmpty(filename))
            
                var index = filename.LastIndexOf(".");
                if (index >= 0)
                    return filename.Substring(index);
            
            return string.Empty;
        
        #endregion

        #region 获取URL参数
        public static string GetParameter(string paraName, string paraValue)
        
            System.Collections.Specialized.NameValueCollection querystring = HttpContext.Current.Request.QueryString;
            System.Text.StringBuilder sb = new System.Text.StringBuilder();
            sb.Append("?");
            if (!string.IsNullOrEmpty(paraValue)) sb.AppendFormat(paraName + "=" + paraValue);
            foreach (string key in querystring.Keys)
            
                if (key != paraName && !string.IsNullOrEmpty(key))
                
                    if (sb.ToString().Length > 1) sb.Append("&");
                    sb.AppendFormat("0=1", key, HttpContext.Current.Server.UrlEncode(querystring[key]));
                

            
            return sb.ToString();
        
        #endregion

        #region 数组转化成逗号隔开的字符串
        /// <summary>
        /// 数组转化成逗号隔开的字符串
        /// </summary>
        /// <param name="arr"></param>
        /// <returns></returns>
        public static string Array2String(string[] arr)
        
            return Array2String(arr, ",");
        

        public static string Array2String(string[] arr, string splitChar)
        
            if (arr != null)
            
                StringBuilder sb = new StringBuilder();
                if (arr != null)
                
                    for (int i = 0; i < arr.Length; i++)
                    
                        sb.Append(arr[i]);
                        if (i + 1 < arr.Length) sb.Append(splitChar);
                    
                
                return sb.ToString();
            
            return string.Empty;
        
        #endregion

        #region 字符串转化为数组
        public static string[] String2Array(string str)
        
            if (!string.IsNullOrEmpty(str))
            
                return str.Split(,);
            
            return null;
        
        #endregion

        #region 数值类型判断
        public static bool IsDecimal(string number)
        
            if (string.IsNullOrEmpty(number)) return false;
            decimal result;
            return Decimal.TryParse(number, out result);
        

        public static bool IsInt(string number)
        
            if (string.IsNullOrEmpty(number)) return false;
            int result;
            return int.TryParse(number, out result);
        
        #endregion

        #region 日期转换
        public static DateTime StringToDateTimeByYYYYMMDD(string time)
        
            if (time.Length == 8)
            
                return new DateTime(int.Parse(time.Substring(0, 4)), int.Parse(time.Substring(4, 2)), int.Parse(time.Substring(6, 2)));
            
            throw new Exception("不合法");
        
        #endregion
#region  函数返回值
        public static Dictionary<int, string> FunctionReturnValue(int code, string messsage)
        
            return new Dictionary<int, string>
                
                    0, code.ToString(),
                    1, messsage ?? string.Empty
                ;
        
        #endregion

        #region 获取支付订单ID
        public static string GetPayOrderID()
        
            char[] s = new char[]  0, 1, 2, 3, 4, 5, 6, 7, 8, 9 ;
            string num = "";
            Random r = new Random();
            for (int i = 0; i < 3; i++)
            
                num += s[r.Next(0, s.Length)].ToString();
            
            string order = DateTime.Now.ToString("yyyyMMddHHmmssfff") + num;
            return order;
        
        #endregion

        #region 冒泡排序法
        public static string[] BubbleSort(string[] r)
        
            int i, j; //交换标志 
            string temp;

            bool exchange;

            for (i = 0; i < r.Length; i++) //最多做R.Length-1趟排序 
            
                exchange = false; //本趟排序开始前,交换标志应为假

                for (j = r.Length - 2; j >= i; j--)
                //交换条件
                    if (System.String.CompareOrdinal(r[j + 1], r[j]) < 0)
                    
                        temp = r[j + 1];
                        r[j + 1] = r[j];
                        r[j] = temp;

                        exchange = true; //发生了交换,故将交换标志置为真 
                    
                

                if (!exchange) //本趟排序未发生交换,提前终止算法 
                
                    break;
                
            
            return r;
        
        #endregion

        #region 指定字节流编码计算MD5哈希值

        /// <summary>
        /// 指定字节流编码计算MD5哈希值
        /// </summary>
        /// <param name="source"></param>
        /// <param name="bytesEncoding"></param>
        /// <returns></returns>
        public static string MD5(string source, Encoding bytesEncoding)
        
            var sourceBytes = bytesEncoding.GetBytes(source);

            var md5 = new MD5CryptoServiceProvider();

            var hashedBytes = md5.ComputeHash(sourceBytes);

            var buffer = new StringBuilder(hashedBytes.Length);

            foreach (byte item in hashedBytes)
                buffer.AppendFormat("0:x2", item);

            return buffer.ToString();
        

        /// <summary>
        /// 指定字节流编码计算MD5哈希值

        /// </summary>
        /// <param name="source"></param>
        /// <returns></returns>
        public static string MD5(string source)
        
            return MD5(source, Encoding.Default);
        
        #endregion

        #region 获取远程服务器ATN结果
        public static String GetHttpResponse(String url)
        
            string strResult;
            try
            
                HttpWebRequest myReq = (HttpWebRequest)HttpWebRequest.Create(url);
                HttpWebResponse HttpWResp = (HttpWebResponse)myReq.GetResponse();
                Stream myStream = HttpWResp.GetResponseStream();
                StreamReader sr = new StreamReader(myStream, Encoding.Default);
                StringBuilder strBuilder = new StringBuilder();
                while (-1 != sr.Peek())
                
                    strBuilder.Append(sr.ReadLine());
                

                strResult = strBuilder.ToString();
            
            catch (Exception exp)
            

                strResult = "错误:" + exp.Message;
            

            return strResult;
        
        #endregion

        #region 数字转大写
        public static string Number2Chinese(int number)
        
            string cstr = "";
            switch (number)
            
                case 1: cstr = ""; break;
                case 2: cstr = ""; break;
                case 3: cstr = ""; break;
                case 4: cstr = ""; break;
                case 5: cstr = ""; break;
                case 6: cstr = ""; break;
                case 7: cstr = ""; break;
                case 8: cstr = ""; break;
                case 9: cstr = ""; break;
                case 10: cstr = ""; break;
            
            return (cstr);
        
        #endregion

        #region 获取IP
        public static string GetClientIP()
        
            return System.Web.HttpContext.Current.Request.UserHostAddress;
        
        #endregion
#region 截取字符串
        public static string Substring(string inputString, int length)
        
            if (!string.IsNullOrEmpty(inputString))
            
                length = inputString.Length < length ? inputString.Length : length;
                return inputString.Substring(0, length);
            
            return string.Empty;
        
        #endregion

        #region 身材随机数字
        public static string GetRandomNumber(int length)
        
            length = length == 0 ? 4 : length;
            char[] s = new char[]  0, 1, 2, 3, 4, 5, 6, 7, 8, 9 ;
            string num = "";
            Random r = new Random();
            for (int i = 0; i < length; i++)
            
                num += s[r.Next(0, s.Length)].ToString();
            
            return num;
        
        #endregion

        #region 写入和获取Cookie
        /// <summary>
        /// 读取Cookie
        /// </summary>
        /// <param name="key"></param>
        /// <returns></returns>
        public static string GetCookie(string key)
        
            if (HttpContext.Current.Request.Cookies[key] == null) return null;
            return HttpContext.Current.Request.Cookies[key].Value;
        

        /// <summary>
        /// 写入Cookie
        /// </summary>
        /// <param name="key"></param>
        /// <param name="value"></param>
        /// <param name="expires"></param>
        public static void WriteCookie(string key, string value, double expires)
        
            HttpCookie Cookie = new HttpCookie(key);
            string host = HttpContext.Current.Request.Url.Host;
            if (host != "localhost")
            
                Cookie.Domain = host.Substring(host.IndexOf(.));
            
            if (expires > 0) Cookie.Expires = DateTime.Now.AddMinutes(expires);

            Cookie.Value = value;
            HttpContext.Current.Response.Cookies.Add(Cookie);
        
        #endregion

        #region 时间转换
        public static double TimeDotNet2Java(DateTime time)
        
            TimeSpan timeSpan = new TimeSpan(time.Ticks - new DateTime(1970, 1, 1, 0, 0, 0).Ticks);
            return (timeSpan.TotalMilliseconds);

        
        #endregion

        #region 判断是否是手机浏览器
        public static bool IsMobileBrowse()
        
            bool isMobile = false;
            string ua = System.Web.HttpContext.Current.Request.UserAgent;
            string[] uas =  "symbian", "android", "iphone", "ucweb", "nokia", "mqqbrowser" ;
            for (var i = 0; i < uas.Length; i++)
            
                if (ua.ToLower().IndexOf(uas[i]) > -1)
                
                    isMobile = true;
                    break;
                
            
            return isMobile;
        
        #endregion

        #region 枚举转化为Dictionary
        public static Dictionary<int, string> BehaviorEnum2Dict()
        
            Dictionary<int, string> dict = new Dictionary<int, string>();
            Type type = typeof(TravelB2B.Core.Utils.BehaviorsEnum);
            foreach (object o in System.Enum.GetValues(type))
            
                dict.Add((int)o, o.ToString());
            
            return dict;
        

        public static Dictionary<int, string> SMSKindEnum2Dict()
        
            Dictionary<int, string> dict = new Dictionary<int, string>();
            Type type = typeof(TravelB2B.Core.Domain.SMSKind);
            foreach (object o in System.Enum.GetValues(type))
            
                dict.Add((int)o, o.ToString());
            
            return dict;
        
        #endregion
  #region 提取中文
        public static string GetChinese(string text)
        
            StringBuilder sb = new StringBuilder();
            int currentcode = -1;
            for (int i = 0; i < text.Length; i++)
            
                currentcode = (int)text[i];
                if (currentcode > 19968 && currentcode < 40869)
                
                    sb.Append(text[i].ToString());
                
            
            return sb.ToString();
        
        #endregion

        #region 获取时间戳
        public static long ConvertDateTimeInt()
        
            return ConvertDateTimeInt(DateTime.Now);
        

        public static long ConvertDateTimeInt(DateTime time)
        
            double intResult = 0;
            System.DateTime startTime = TimeZone.CurrentTimeZone.ToLocalTime(new System.DateTime(1970, 1, 1));
            intResult = (time - startTime).TotalSeconds;
            return (long)intResult;
        
        #endregion

        #region Base64加密解密
        public static string EncodeBase64(Encoding encode, string source)
        
            string code = source;
            byte[] bytes = encode.GetBytes(source);
            try
            
                code = Convert.ToBase64String(bytes);
            
            catch
            
                code = source;
            
            return code;
        

        /// <summary>
        /// Base64加密,采用utf8编码方式加密
        /// </summary>
        /// <param name="source">待加密的明文</param>
        /// <returns>加密后的字符串</returns>
        public static string EncodeBase64(string source)
        
            return EncodeBase64(Encoding.UTF8, source);
        

        /// <summary>
        /// Base64解密
        /// </summary>
        /// <param name="codeName">解密采用的编码方式,注意和加密时采用的方式一致</param>
        /// <param name="result">待解密的密文</param>
        /// <returns>解密后的字符串</returns>
        public static string DecodeBase64(Encoding encode, string result)
        
            string decode = "";
            byte[] bytes = Convert.FromBase64String(result);
            try
            
                decode = encode.GetString(bytes);
            
            catch
            
                decode = result;
            
            return decode;
        

        /// <summary>
        /// Base64解密,采用utf8编码方式解密
        /// </summary>
        /// <param name="result">待解密的密文</param>
        /// <returns>解密后的字符串</returns>
        public static string DecodeBase64(string result)
        
            return DecodeBase64(Encoding.UTF8, result);
        
        #endregion

        #region Base64加密解密
        public static string EncodeBase64(Encoding encode, string source)
        
            string code = source;
            byte[] bytes = encode.GetBytes(source);
            try
            
                code = Convert.ToBase64String(bytes);
            
            catch
            
                code = source;
            
            return code;
        

        /// <summary>
        /// Base64加密,采用utf8编码方式加密
        /// </summary>
        /// <param name="source">待加密的明文</param>
        /// <returns>加密后的字符串</returns>
        public static string EncodeBase64(string source)
        
            return EncodeBase64(Encoding.UTF8, source);
        

        /// <summary>
        /// Base64解密
        /// </summary>
        /// <param name="codeName">解密采用的编码方式,注意和加密时采用的方式一致</param>
        /// <param name="result">待解密的密文</param>
        /// <returns>解密后的字符串</returns>
        public static string DecodeBase64(Encoding encode, string result)
        
            string decode = "";
            byte[] bytes = Convert.FromBase64String(result);
            try
            
                decode = encode.GetString(bytes);
            
            catch
            
                decode = result;
            
            return decode;
        

        /// <summary>
        /// Base64解密,采用utf8编码方式解密
        /// </summary>
        /// <param name="result">待解密的密文</param>
        /// <returns>解密后的字符串</returns>
        public static string DecodeBase64(string result)
        
            return DecodeBase64(Encoding.UTF8, result);
        
        #endregion

        #region 是否是微信访问
        public static bool IsMicroMessenger()
        
            string userAgent = System.Web.HttpContext.Current.Request.UserAgent;
            return userAgent.IndexOf("MicroMessenger") > -1;
        
        #endregion 

        #region 获取Post数据
        /// <summary>
        /// 获取Post数据
        /// </summary>
        /// <returns></returns>
        public static string GetHttpPostData()
        
            string requestData = "";
            using (Stream recieveStream = HttpContext.Current.Request.InputStream)
            
                using (StreamReader readStream = new StreamReader(recieveStream, Encoding.UTF8))
                
                    requestData = readStream.ReadToEnd();
                
            
            return requestData;
        
        #endregion 

        #region 在一个字符串中查找图片的src的值,返回一个数组
        public static string[] GetSrc(string str)
        
            string regStr = "\\<IMG\\ [\\s\\S]*?src=[‘\"]?(?<p>[^‘\"\\>\\ ]+)[‘\"\\>\\ ]";
            string cont1 = string.Empty; //图片的src
            Regex reg = new Regex(regStr, RegexOptions.Compiled | RegexOptions.IgnoreCase);
            Match match = reg.Match(str);
            string picSrc = "";
            while (match.Success)
            
                picSrc = match.Groups["p"].Value;
                cont1 += string.Format("0", picSrc + ",");
                match = match.NextMatch();
            
            cont1 = cont1.Substring(0, cont1.LastIndexOf(,));
            string[] strList = cont1.Split(,);
            return strList;
        
        #endregion

        #region 获取一个图片的宽和高
        public static int[] PictureAttribute(string filePath)
        
            int[] picture = new int[2];
            Image pic = Image.FromFile(filePath);//filePath是该图片的绝对路径
            picture[0] = pic.Width;//长度像素值
            picture[1] = pic.Height;//高度像素值 
            return picture;
        
        #endregion

        #region 提取图片地址
        public static string[] GethtmlImageUrlList(string htmlText)
        
            Regex regImg = new Regex(@"<img\b[^<>]*?\bsrc[\s\t\r\n]*=[\s\t\r\n]*[""‘]?[\s\t\r\n]*(?<imgUrl>[^\s\t\r\n""‘<>]*)[^<>]*?/?[\s\t\r\n]*>", RegexOptions.IgnoreCase);
            //新建一个matches的MatchCollection对象 保存 匹配对象个数(img标签)  
            MatchCollection matches = regImg.Matches(htmlText);
            int i = 0;
            string[] sUrlList = new string[matches.Count];
            //遍历所有的img标签对象  
            foreach (Match match in matches)
            
                //获取所有Img的路径src,并保存到数组中  
                sUrlList[i++] = match.Groups["imgUrl"].Value;
            
            return sUrlList;
        
        #endregion

        //20180720 王鑫
        #region 国内手机号格式校验
        public static bool CheckMobliePhone(string phone)
        
            //电信手机号码正则        
            string dianxin = @"^1[3578][01379]\d8$";
            Regex dReg = new Regex(dianxin);
            //联通手机号正则        
            string liantong = @"^1[34578][01256]\d8$";
            Regex tReg = new Regex(liantong);
            //移动手机号正则        
            string yidong = @"^(134[012345678]\d7|1[34578][012356789]\d8)$";
            Regex yReg = new Regex(yidong);

            if (dReg.IsMatch(phone) || tReg.IsMatch(phone) || yReg.IsMatch(phone))
            
                return true;
            
            return false;
        
        #endregion

        //20180810 王鑫
        #region 渲染二维码
        public static Bitmap RenderQrCode(string str)
        
            QRCodeGenerator.ECCLevel eccLevel = QRCodeGenerator.ECCLevel.L;
            using (QRCodeGenerator qrGenerator = new QRCodeGenerator())
            
                using (QRCodeData qrCodeData = qrGenerator.CreateQrCode(str, eccLevel))
                
                    using (QRCode qrCode = new QRCode(qrCodeData))
                    
                        return qrCode.GetGraphic(8, Color.Black, Color.White, false);

                    
                
            

        
        #endregion
   #region 网络图片到流的转换
        public static string FileToStream(string SourFilePath)
        
            try
            
                WebRequest request = WebRequest.Create(SourFilePath);
                WebResponse response = request.GetResponse();
                Stream s = response.GetResponseStream();
                byte[] data = new byte[1024];
                int length = 0;
                MemoryStream ms = new MemoryStream();
                while ((length = s.Read(data, 0, data.Length)) > 0)
                
                    ms.Write(data, 0, length);
                
                ms.Seek(0, SeekOrigin.Begin);
                var image = Image.FromStream(ms);
                var bytedata = ImageTobyte(image);
                string base64 = Convert.ToBase64String(bytedata);

                return base64;
            
            catch (Exception ex)
            
                logger.Error(ex.Message);
                throw ex;
            
        

        private static byte[] ImageTobyte(Image image)
        
            MemoryStream ms = new MemoryStream();
            Bitmap bi = new Bitmap(image);
            bi.Save(ms, image.RawFormat);
            byte[] data = new byte[ms.Length];
            ms.Seek(0, SeekOrigin.Begin);
            ms.Read(data, 0, data.Length);
            return data;
        
        #endregion


        #region 根据相对路径在项目根路径下创建文件夹
        //根据相对路径在项目根路径下创建文件夹
        private bool CreateFolderIfNeeded(string path)
        
            bool result = true;
            if (!Directory.Exists(path))
            
                try
                
                    Directory.CreateDirectory(path);
                
                catch (Exception)
                
                    result = false;
                
            
            return result;
        
        #endregion

 

#region 密码加密
        public static String EncryptPassword(String password, String salt)
        
            var bytes = Encoding.UTF8.GetBytes(password + salt);
            byte[] hashBytes = new System.Security.Cryptography.SHA256Managed().ComputeHash(bytes);
            string hashString = Convert.ToBase64String(hashBytes);
            return hashString;
        

#endregion

 

以上是关于共用方法整理的主要内容,如果未能解决你的问题,请参考以下文章

求iis与apache共用80端口方法的详细方法

多个网站共用相同一级域名80端口的方法

Thinkphp3.2多站点共用S方法缓存

vue.js 组件共用函数的方法之一

laravel 控制器多个方法共用一个路由

结构体及共用体的初始化方法