首页 > 技术文章 > 字符串帮助类:StringExtensions

wzq806341010 2014-02-11 10:38 原文

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Net;
using System.IO;
using System.Security.Cryptography;
using System.Net.Mail;

namespace passport.core.Tool
{
    public static class StringExtensions
    {
        #region AsNull
        /// <summary>
        /// 如果字符串为空怎转换为NULL
        /// </summary>
        /// <param name="items"></param>
        /// <returns></returns>
        public static string AsNullIfEmpty(this string items)
        {
            return string.IsNullOrEmpty(items) ? null : items;
        }
        /// <summary>
        /// 如果字符串为空,空白字符则转换为NULL
        /// </summary>
        /// <param name="items"></param>
        /// <returns></returns>
        public static string AsNullIfWhiteSpace(this string items)
        {
            return string.IsNullOrWhiteSpace(items) ? null : items;
        }

        #endregion

        /// <summary>
        /// 截取字符串
        /// </summary>
        /// <param name="str">字符串</param>
        /// <param name="len">长度</param>
        /// <returns></returns>
        public static string CutString(this string str, int len)
        {
            if (string.IsNullOrWhiteSpace(str))
                return string.Empty;
            else
            {
                if (str.Length > len)
                    return str.Substring(0, len);
                else
                {
                    return str;
                }
            }
        }

        #region 截取字符串
        /// <summary>
        /// 截取字符串
        /// </summary>
        /// <param name="text">原字符串</param>
        /// <param name="characterCount">截取长度</param>
        /// <returns></returns>
        public static string Ellipsize(this string text, int characterCount)
        {
            return text.Ellipsize(characterCount, "&#160;&#8230;");
        }
        /// <summary>
        /// 截取字符串
        /// </summary>
        /// <param name="text">原字符串</param>
        /// <param name="characterCount">截取长度</param>
        /// <param name="ellipsis">省略部分</param>
        /// <returns></returns>
        public static string Ellipsize(this string text, int characterCount, string ellipsis)
        {
            if (string.IsNullOrWhiteSpace(text))
                return "";

            if (characterCount < 0 || text.Length <= characterCount)
                return text;

            return Regex.Replace(text.Substring(0, characterCount + 1), @"\s+\S*$", "") + ellipsis;
        }
        #endregion

        /// <summary>
        /// 移除HTML标签
        /// </summary>
        /// <param name="html"></param>
        /// <returns></returns>
        public static string RemoveTags(this string html)
        {
            return string.IsNullOrEmpty(html)
                ? ""
                : Regex.Replace(html, "<[^<>]*>", "", RegexOptions.Singleline);
        }

        /// <summary>
        /// 去Html标签
        /// </summary>
        /// <param name="Htmlstring"></param>
        /// <returns></returns>
        public static string ToNoHtmlString(this string Htmlstring)
        {
            //删除脚本
            Htmlstring = Regex.Replace(Htmlstring, @"<script[^>]*?>.*?</script>", "", RegexOptions.IgnoreCase);
            //删除HTML
            Htmlstring = Regex.Replace(Htmlstring, @"<(.[^>]*)>", "", RegexOptions.IgnoreCase);
            Htmlstring = Regex.Replace(Htmlstring, @"([\r\n])[\s]+", "", RegexOptions.IgnoreCase);
            Htmlstring = Regex.Replace(Htmlstring, @"-->", "", RegexOptions.IgnoreCase);
            Htmlstring = Regex.Replace(Htmlstring, @"<!--.*", "", RegexOptions.IgnoreCase);
            Htmlstring = Regex.Replace(Htmlstring, @"&(quot|#34);", "\"", RegexOptions.IgnoreCase);
            Htmlstring = Regex.Replace(Htmlstring, @"&(amp|#38);", "&", RegexOptions.IgnoreCase);
            Htmlstring = Regex.Replace(Htmlstring, @"&(lt|#60);", "<", RegexOptions.IgnoreCase);
            Htmlstring = Regex.Replace(Htmlstring, @"&(gt|#62);", ">", RegexOptions.IgnoreCase);
            Htmlstring = Regex.Replace(Htmlstring, @"&(nbsp|#160);", "   ", RegexOptions.IgnoreCase);
            Htmlstring = Regex.Replace(Htmlstring, @"&(iexcl|#161);", "\xa1", RegexOptions.IgnoreCase);
            Htmlstring = Regex.Replace(Htmlstring, @"&(cent|#162);", "\xa2", RegexOptions.IgnoreCase);
            Htmlstring = Regex.Replace(Htmlstring, @"&(pound|#163);", "\xa3", RegexOptions.IgnoreCase);
            Htmlstring = Regex.Replace(Htmlstring, @"&(copy|#169);", "\xa9", RegexOptions.IgnoreCase);
            Htmlstring = Regex.Replace(Htmlstring, @"&#(\d+);", "", RegexOptions.IgnoreCase);
            Htmlstring.Replace("<", "");
            Htmlstring.Replace(">", "");
            Htmlstring.Replace("\r\n", "");
            //Htmlstring = HttpContext.Current.Server.HtmlEncode(Htmlstring).Trim();

            return Htmlstring;
        }




        /// <summary>
        /// 拆分成数组
        /// </summary>
        /// <param name="str">原字符串</param>
        /// <param name="strSplit">分隔字符</param>
        /// <returns>字符串数组</returns>
        public static string[] Split(this string str, string strSplit)
        {
            if (str.IndexOf(strSplit) < 0)
            {
                string[] tmp = { str };
                return tmp;
            }
            return Regex.Split(str, Regex.Escape(strSplit), RegexOptions.IgnoreCase);
        }

        public static string MakeTinyUrl(this string Url)
        {
            try
            {
                if (!Url.ToLower().StartsWith("http") && !Url.ToLower().StartsWith("ftp"))
                {
                    Url = "http://" + Url;
                }
                var request = WebRequest.Create("http://*****.net/api-create?url=" + System.Web.HttpUtility.UrlPathEncode(Url));
                var res = request.GetResponse();
                string text;
                using (var reader = new StreamReader(res.GetResponseStream()))
                {
                    text = reader.ReadToEnd();
                }
                return text;
            }
            catch (Exception)
            {
                return Url;
            }
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="text"></param>
        /// <returns></returns>
        public static string ConvertMessageToHtml(this string text)
        {
            if (string.IsNullOrEmpty(text))
            {
                return string.Empty;
            }
            var UsernameExpression = new Regex(@"^(@[a-zA-Z_0-9]*)|(\s@[a-zA-Z_0-9]*)|(\s@[a-zA-Z_0-9]*)$", RegexOptions.Compiled | RegexOptions.IgnoreCase | RegexOptions.Singleline);

            var _html = UsernameExpression.Replace(text,
                                                    match =>
                                                        string.Format("{1}@<a href='/{0}'>{0}</a>",
                                                                       match.ToString().Trim().Substring(1),
                                                                       (match.ToString().StartsWith("@") ? "" : " ")));

            var UrlExpression = new Regex(@"((http|ftp|https):\/\/)?[\w\-_]+(\.[\w\-_]+)+([\w\-\.,@?^=%&amp;:/~\+#]*[\w\-\@?^=%&amp;/~\+#])?", RegexOptions.Compiled | RegexOptions.IgnoreCase | RegexOptions.Singleline);
            _html = UrlExpression.Replace(_html,
                                            match =>
                                            MakeTinyUrl(match.ToString()));

            _html = UrlExpression.Replace(_html,
                                          match =>
                                          string.Format("<a href='{0}' target='_blank'>{1}</a>",
                                                        match.ToString().ToLower().StartsWith("http") ? match.ToString() : string.Format("http://{0}", match.ToString()),
                                                        match.ToString()));


            //var topExpression = new Regex(@"#\w{0,10}#", RegexOptions.Compiled | RegexOptions.IgnoreCase | RegexOptions.Singleline);
            //_html = topExpression.Replace(_html,
            //                                match =>
            //                                    string.Format("<a href='{0}'>{1}</a>",
            //                                                   System.Web.HttpUtility.UrlPathEncode(match.ToString().Trim().Trim('#')),
            //                                                   match.ToString()));
            // _html = _html.Replace("'", "\"");
            return _html;
        }


        #region 字符串进行编码

        /// <summary>
        /// 把字符串转换成BASE64
        /// </summary>
        /// <param name="str"></param>
        /// <returns></returns>
        public static string EncodeBase64(this string str)
        {
            return Convert.ToBase64String(str.ToByteArray<System.Text.UTF8Encoding>());
        }
        /// <summary>
        /// 把BASE64转换成字符串
        /// </summary>
        /// <param name="str"></param>
        /// <returns></returns>
        public static string DecodeBase64(this string str)
        {
            return System.Text.UTF8Encoding.ASCII.GetString(Convert.FromBase64String(str));
        }
        /// <summary>
        /// 对URL字符串进行编码(UTF-8)
        /// </summary>
        /// <param name="url"></param>
        /// <returns></returns>
        public static string UrlEncode(this string url)
        {
            if (string.IsNullOrEmpty(url)) return string.Empty;
            return System.Web.HttpUtility.UrlEncode(url, System.Text.Encoding.UTF8);
        }
        /// <summary>
        /// 对URL字符串进行解码(UTF-8)
        /// </summary>
        /// <param name="str"></param>
        /// <returns></returns>
        public static string UrlDecode(this string str)
        {
            if (string.IsNullOrEmpty(str)) return string.Empty;
            return System.Web.HttpUtility.UrlDecode(str, System.Text.Encoding.UTF8);
        }
        #endregion

        #region 字符串转换为字节数
        /// <summary>
        /// 字符串转换为字节数组
        /// </summary>
        /// <typeparam name="encoding">编码</typeparam>
        /// <param name="str"></param>
        /// <returns></returns>
        public static byte[] ToByteArray<encoding>(this string str) where encoding : Encoding
        {
            Encoding enc = Activator.CreateInstance<encoding>();
            return enc.GetBytes(str);
        }

        /// <summary>
        /// 字符串转换为字节数组(UTF8)
        /// </summary>
        /// <param name="str"></param>
        /// <returns></returns>
        public static byte[] ToByteArray(this string str)
        {
            return str.ToByteArray<System.Text.UTF8Encoding>();
        }

        /// <summary>
        /// 字符串转换为字节序列(UTF8)
        /// </summary>
        /// <param name="str"></param>
        /// <returns></returns>
        public static Stream ToStream(this string str)
        {
            return str.ToStream<System.Text.UTF8Encoding>();
        }

        /// <summary>
        /// 字符串转换为字节序列
        /// </summary>
        /// <typeparam name="encoding">编码</typeparam>
        /// <param name="str"></param>
        /// <returns></returns>
        public static Stream ToStream<encoding>(this string str) where encoding : Encoding
        {
            byte[] bytes = str.ToByteArray<encoding>();
            return new System.IO.MemoryStream(bytes);
        }
        #endregion

        #region 验证

        /// <summary>
        /// 验证整数
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        public static bool IsValidNumber(this String input)
        {
            return ValidateString(input, @"^[1-9]{1}[0-9]{0,9}$");
        }

        /// <summary>
        /// 验证是否日期
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        public static bool IsValidDate(this String input)
        {
            bool bValid = ValidateString(input, @"^[12]{1}(\d){3}[-][01]?(\d){1}[-][0123]?(\d){1}$");
            return (bValid && input.CompareTo("1753-01-01") >= 0);
        }

        /// <summary>
        /// 验证EMAIL
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        public static bool IsValidEmail(this String input)
        {
            return ValidateString(input, @"^([\w-\.]+)@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([\w-]+\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\]?)$");
        }

        /// <summary>
        /// 验证EMAIL
        /// </summary>
        /// <param name="input"></param>
        /// <param name="expression"></param>
        /// <returns></returns>
        public static bool IsValidEmail(this String input, String expression)
        {
            if (string.IsNullOrEmpty(input)) return false;
            if (String.IsNullOrEmpty(expression))
            {
                expression = @"\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*";
            }
            return ValidateString(input, expression);
        }

        /// <summary>
        /// 验证是否手机号码
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        public static bool IsValidMobile(this String input)
        {
            if (string.IsNullOrEmpty(input)) return false;
            return ValidateString(input, "^0{0,1}(1[3-8])[0-9]{9}$");
        }

        internal static Boolean ValidateString(String input, String expression)
        {
            Regex validator = new Regex(expression, RegexOptions.None);
            return validator.IsMatch(input);
        }

        #endregion


        #region 加密/解密


        /// <summary>
        /// 对称密钥加密
        /// </summary>
        /// <typeparam name="Algorithm"></typeparam>
        /// <param name="str"></param>
        /// <param name="key"></param>
        /// <returns></returns>
        public static string Encrypt<Algorithm>(this string str, string key)
            where Algorithm : SymmetricAlgorithm
        {
            return str.Encrypt<Algorithm, System.Text.UTF8Encoding>(key);
        }


        /// <summary>
        /// 对称密钥加密
        /// </summary>
        /// <typeparam name="Algorithm"></typeparam>
        /// <typeparam name="StringEncoding"></typeparam>
        /// <param name="str"></param>
        /// <param name="key"></param>
        /// <returns></returns>
        public static string Encrypt<Algorithm, StringEncoding>(this string str, string key)
            where Algorithm : SymmetricAlgorithm
            where StringEncoding : Encoding
        {
            Stream s = new System.IO.MemoryStream(str.ToByteArray());
            Stream encryptedStream = s.Encrypt<Algorithm>(key.ToByteArray());
            byte[] bytes = encryptedStream.ToByteArray();
            return Convert.ToBase64String(bytes);
        }

        /// <summary>
        /// 对称密钥解密
        /// </summary>
        /// <typeparam name="Algorithm"></typeparam>
        /// <param name="str"></param>
        /// <param name="key"></param>
        /// <returns></returns>
        public static string Decrypt<Algorithm>(this string str, string key)
            where Algorithm : SymmetricAlgorithm
        {
            return str.Decrypt<Algorithm, System.Text.UTF8Encoding>(key);
        }
        /// <summary>
        /// 对称密钥解密
        /// </summary>
        /// <typeparam name="Algorithm">对称加密算法</typeparam>
        /// <typeparam name="StringEncoding">字符编码</typeparam>
        /// <param name="str"></param>
        /// <param name="key"></param>
        /// <returns></returns>
        public static string Decrypt<Algorithm, StringEncoding>(this string str, string key)
            where Algorithm : SymmetricAlgorithm
            where StringEncoding : Encoding
        {
            Stream s = new System.IO.MemoryStream(Convert.FromBase64String(str));
            Stream decryptedStream = s.Decrypt<Algorithm>(key.ToByteArray());
            byte[] bytes = decryptedStream.ToByteArray();
            return Activator.CreateInstance<StringEncoding>().GetString(bytes);
        }

        /// <summary>
        /// 不可逆加密
        /// </summary>
        /// <typeparam name="Algorithm">加密HASH算法</typeparam>
        /// <typeparam name="StringEncoding">字符编码</typeparam>
        /// <param name="str"></param>
        /// <returns></returns>
        public static string EncryptOneWay<Algorithm, StringEncoding>(this string str)
            where Algorithm : HashAlgorithm
            where StringEncoding : Encoding
        {
            Encoding enco = Activator.CreateInstance<StringEncoding>();
            byte[] inputBye = enco.GetBytes(str);
            byte[] bytes = Activator.CreateInstance<Algorithm>().ComputeHash(inputBye);
            return System.BitConverter.ToString(bytes).Replace("-", ""); ;
        }
        /// <summary>
        /// 不可逆加密
        /// </summary>
        /// <typeparam name="Algorithm">加密HASH算法</typeparam>
        /// <param name="str">字符编码</param>
        /// <returns></returns>
        public static string EncryptOneWay<Algorithm>(this string str)
            where Algorithm : HashAlgorithm
        {
            return str.EncryptOneWay<Algorithm, System.Text.UTF8Encoding>();
        }

        /// <summary>
        /// MD5编码
        /// </summary>
        /// <param name="text"></param>
        /// <returns></returns>
        public static string MD5(this string text)
        {
            return text.EncryptOneWay<MD5CryptoServiceProvider, UTF8Encoding>().ToLower();
        }

        public static string SHA512(this string text)
        {
            return text.EncryptOneWay<SHA512Cng, UTF8Encoding>();
        }
        public static string SHA256(this string text)
        {
            return text.EncryptOneWay<SHA256Cng, UTF8Encoding>();
        }
        #endregion


        /// <summary>
        /// 发送邮件方法
        /// </summary>
        /// <param name="content">内容</param>
        /// <param name="title">标题</param>
        /// <param name="from">发送方</param>
        /// <param name="to">接收方</param>
        /// <returns></returns>
        public static bool SendEmail(this string content, string title, string from, string to)
        {
            SmtpClient _smtpClient = new SmtpClient();
            _smtpClient.DeliveryMethod = SmtpDeliveryMethod.Network;//指定电子邮件发送方式
            _smtpClient.Host =Framework.Helper.Config.Instance.GetAppSetting<string>("mail-Host", "smtp.126.com");//指定SMTP服务器
            string _userName =Framework.Helper.Config.Instance.GetAppSetting<string>("mail-userName", "******@126.com");
            string _userPwd =Framework.Helper.Config.Instance.GetAppSetting<string>("mail-userPwd", "******");
            _smtpClient.Credentials = new System.Net.NetworkCredential(_userName, _userPwd);//用户名和密码

            MailMessage _mailMessage = new MailMessage(from, to);
            _mailMessage.Subject = title;//主题
            _mailMessage.Body = content;//内容
            _mailMessage.BodyEncoding = System.Text.Encoding.UTF8;//正文编码
            _mailMessage.IsBodyHtml = true;//设置为HTML格式
            _mailMessage.Priority = MailPriority.High;//优先级    
            try
            {
                _smtpClient.Send(_mailMessage);
                return true;
            }
            catch (Exception ex)
            {
                return false;
            }
        }
    }
}

 

推荐阅读