using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Text;
using System.Text.RegularExpressions;
using System.Security.Cryptography;
using System.IO;

namespace Utility
{
    public class StrManage
    {
        private static Regex RegPwd = new Regex(@"^[A-Za-z0-9]{6,16}$");
        private static Regex RegNumber = new Regex("^[0-9]+$");
        private static Regex RegNumberSign = new Regex("^[+-]?[0-9]+$");
        private static Regex RegDecimal = new Regex("^[0-9]+[.]?[0-9]+$");
        private static Regex RegDecimalSign = new Regex("^[+-]?[0-9]+[.]?[0-9]+$"); //等价于^[+-]?\d+[.]?\d+$       
        private static Regex RegEmail = new Regex(@"^\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*$" );//w 英文字母或数字的字符串，和 [a-zA-Z0-9] 语法一样 
        private static Regex RegCHZN = new Regex("[\u4e00-\u9fa5]");

        public StrManage()
        {
        }

        #region 简单转换UBB代码

        /// <summary>
        /// 简单转换UBB(包括换行的处理)
        /// </summary>
        /// <param name="str"></param>
        /// <returns></returns>
        public static string dntUbb2Html(string str)
        {
            str = Regex.Replace(str, @"\[url](?<url>.+?)\[/url]", "<a   href=${url}   target=_blank>${url}</a>", RegexOptions.IgnoreCase);
            str = Regex.Replace(str, @"\[url=(?<url>.+?)](?<name>.+?)\[/url]", "<a   href=${url}   target=_blank>${name}</a>", RegexOptions.IgnoreCase);
            str = Regex.Replace(str, @"\[email](?<email>.+?)\[/email]", "<a   href=mailt${email}   target=_blank>${email}</a>", RegexOptions.IgnoreCase);
            str = Regex.Replace(str, @"\[email=(?<email>.+?)](?<name>.+?)\[/email]", "<a   href=mailt${email}   target=_blank>${name}</a>", RegexOptions.IgnoreCase);
            str = Regex.Replace(str, @"\[flash](?<flash>.+?)\[/flash]", "<div   style=width:640;text-align:left><a   href=${flash}>[\u5168\u5c4f\u67e5\u770b]</a></div><object   codebase=http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=4,0,2,0   classid=clsid:d27cdb6e-ae6d-11cf-96b8-444553540000   width=640   height=480><param   name=movie   value=${flash}><param   name=quality   value=high><embed   src=${flash}   quality=high   pluginspage=http://www.macromedia.com/shockwave/download/index.cgi?p1_prod_version=shockwaveflash   type=application/x-shockwave-flash   width=640   height=480></embed></object>", RegexOptions.IgnoreCase);
            str = Regex.Replace(str, @"\[dir=(?<width>[0-9]+?),(?<height>[0-9]+?)](?<url>.+?)\[/dir]", "<object   classid=clsid:166b1bca-3f9c-11cf-8075-444553540000   codebase=http://download.macromedia.com/pub/shockwave/cabs/director/sw.cab#version=7,0,2,0   width=${width}   height=${height}><param   name=src   value=${url}><embed   src=${url}   pluginspage=http://www.macromedia.com/shockwave/download/   width=${width}   height=${height}></embed></object>", RegexOptions.IgnoreCase);
            str = Regex.Replace(str, @"\[rm=(?<width>[0-9]+?),(?<height>[0-9]+?)](?<url>.+?)\[/rm]", "<object   classid=clsid:cfcdaa03-8be4-11cf-b84b-0020afbbccfa   class=object   id=raocx   width=${width}   height=${height}><param   name=src   value=${url}><param   name=console   value=clip1><param   name=controls   value=imagewindow><param   name=autostart   value=true></object><br><object   classid=clsid:cfcdaa03-8be4-11cf-b84b-0020afbbccfa   height=32   id=video2   width=${width}><param   name=src   value=${url}><param   name=autostart   value=-1><param   name=controls   value=controlpanel><param   name=console   value=clip1></object>", RegexOptions.IgnoreCase);
            str = Regex.Replace(str, @"\[mp=(?<width>[0-9]+?),(?<height>[0-9]+?)](?<url>.+?)\[/mp]", "<object   align=middle   classid=clsid:22d6f312-b0f6-11d0-94ab-0080c74c7e95   class=object   id=mediaplayer   width=${width}   height=${height}   ><param   name=showstatusbar   value=-1><param   name=filename   value=${url}><embed   type=application/x-oleobject   codebase=http://activex.microsoft.com/activex/controls/mplayer/en/nsmp2inf.cab#version=5,1,52,701   flename=mp   src=${url}   width=${width}   height=${height}></embed></object>", RegexOptions.IgnoreCase);
            str = Regex.Replace(str, @"\[qt=(?<width>[0-9]+?),(?<height>[0-9]+?)](?<url>.+?)\[/qt]", "<embed   src=${url}   width=${width}   height=${height}   autoplay=true   loop=false   controller=true   playeveryframe=false   cache=false   scale=tofit   bgcolor=#000000   kioskmode=false   targetcache=false   pluginspage=http://www.apple.com/quicktime/>", RegexOptions.IgnoreCase);
            str = Regex.Replace(str, @"\[img](?<img>.+?)\[/img]", "<a   href=${img}   target=_blank><img   src=${img}   border=0   ></a>", RegexOptions.IgnoreCase);
            str = Regex.Replace(str, @"\[color=(?<color>.+?)](?<text>.+?)\[/color]", "<font   color=${color}>${text}</font>", RegexOptions.IgnoreCase);
            str = Regex.Replace(str, @"\[face=(?<face>.+?)](?<text>.+?)\[/face]", "<font   face=${face}>${text}</font>", RegexOptions.IgnoreCase);
            str = Regex.Replace(str, @"\[down=(?<file>.+?)](?<text>.+?)\[/down]", "<a   href=${file}   target=_blank>${text}</a>", RegexOptions.IgnoreCase);
            str = Regex.Replace(str, @"\[align=(?<align>.+?)](?<text>.+?)\[/align]", "<div   align=${align}>${text}</div>", RegexOptions.IgnoreCase);
            str = Regex.Replace(str, @"\[quote](?<text>.+?)\[/quote]", "<div   class=quote>${text}</div>", RegexOptions.IgnoreCase);
            str = Regex.Replace(str, @"\[i](?<text>.+?)\[/i]", "<i>${text}</i>", RegexOptions.IgnoreCase);
            str = Regex.Replace(str, @"\[u](?<text>.+?)\[/u]", "<u>${text}</u>", RegexOptions.IgnoreCase);
            str = Regex.Replace(str, @"\[b](?<text>.+?)\[/b]", "<b>${text}</b>", RegexOptions.IgnoreCase);
            str = Regex.Replace(str, @"\[size=(?<size>.+?)](?<text>.+?)\[/size]", "<font   size=${size}>${text}</font>", RegexOptions.IgnoreCase);
            str = Regex.Replace(str, @"\[\*](?<text>.+?)\[/\*]", "<li>${text}</li>", RegexOptions.IgnoreCase);
            str = Regex.Replace(str, @"\[list](?<text>.+?)\[/list]", "<ul>${text}</ul>", RegexOptions.IgnoreCase);
            str = Regex.Replace(str, @"\[list=(?<type>.+?)](?<text>.+?)\[/list]", "<ol   type=${type}>${text}</ol   id=${type}>", RegexOptions.IgnoreCase);

            str = Regex.Replace(str, "\r\n", "<br />");
            str = Regex.Replace(str, "<br /><br />", "<br />");
            return str;
        }

        #endregion

        #region 替换论坛调用title中的html字符

        /// <summary>
        /// 替换论坛调用title中的html字符
        /// </summary>
        /// <param name="strTemp"></param>
        /// <returns></returns>
        public static string repDntTopicTitle(string strTemp)
        {
            strTemp = strTemp.Replace("<span style=\"font-weight:bold;\">","");
            strTemp = strTemp.Replace("</span>","");


            //处理post列表中的UBB

            strTemp = strTemp.Replace("[b]", "");
            strTemp = strTemp.Replace("[/b]", "");

            strTemp = strTemp.Replace("[i]", "");
            strTemp = strTemp.Replace("[/i]", "");

            strTemp = strTemp.Replace("[code]", "");
            strTemp = strTemp.Replace("[/code]", "");


            return strTemp;

        }
        #endregion

        #region html代码转化51aspxUBB
        public static string Html2myUBB(string strTmp)
        {
            strTmp = strTmp.Replace("<","&lt;")
		    .Replace(">","&gt;")
		    .Replace(" ","&nbsp;")
		    .Replace("  ","&nbsp;")
		    .Replace("[$B]","<b>")
		    .Replace("[/$B]","</b>")
		    .Replace("[$I]","<i>")
		    .Replace("[/$I]","</i>")	
		    .Replace("[$U]","<u>")
		    .Replace("[/$U]","</u>")	
		    .Replace("[$URL]","<a href=")
		    .Replace("[/$URL]"," target=_blank>[查看链接]</a>")	
		    .Replace("[$IMG]","<img src=")
		    .Replace("[/$IMG]"," />")	
		    .Replace("[$CODE]","<div class=\"code\">")	
		    .Replace("[/$CODE]","</div>")
		    .Replace("/\r\n/g","<br />");
            return strTmp;
        }

        #endregion

        #region Html转换到UBB处理
        /// <summary>
        /// 把html转换到ubb
        /// </summary>
        /// <param name="obj"></param>
        /// <returns></returns>
        public static string Html2Ubb(object obj)
        {
            string s = obj.ToString();
            s = Regex.Replace(s, @"<br\s*\/?>", "\r\n", RegexOptions.IgnoreCase);
            s = Regex.Replace(s, @"<hr\s*\/?>", "[line]1,#dddddd[/line]", RegexOptions.IgnoreCase);
            s = Regex.Replace(s, @"<p[^>]*>", "", RegexOptions.IgnoreCase);
            s = Regex.Replace(s, @"<\/p>", "\r\n", RegexOptions.IgnoreCase);
            s = Regex.Replace(s, @"<\/?font[^>]*>", "", RegexOptions.IgnoreCase);
            s = Regex.Replace(s, @"<(\/?)b>", "[$1b]", RegexOptions.IgnoreCase);
            s = Regex.Replace(s, @"<(\/?)strong>", "[$1b]", RegexOptions.IgnoreCase);
            s = Regex.Replace(s, @"<(\/?)i>", "[$1i]", RegexOptions.IgnoreCase);
            s = Regex.Replace(s, @"\[\/?align[=a-zA-Z]*\]", "", RegexOptions.IgnoreCase);
            s = Regex.Replace(s, @"<a href=""([^""]*)""[^>]*>([^<]+)<\/a>", "[url=$1]$2[/url]", RegexOptions.IgnoreCase);
            s = Regex.Replace(s, @"<a href='([^']*)'[^>]*>([^<]+)<\/a>", "[url=$1]$2[/url]", RegexOptions.IgnoreCase);
            s = Regex.Replace(s, @"<img src=""([^""]*)""[^>]*>", "[img]$1[/img]", RegexOptions.IgnoreCase);
            s = Regex.Replace(s, @"\[MP=([\d]*),([\d]*),[a-zA-Z]*\]", "[MP=$1,$2]", RegexOptions.IgnoreCase);
            s = Regex.Replace(s, @"\[upload=[a-zA-Z]+\]([^\[]+)\[\/upload\]", "[img]$1[/img]", RegexOptions.IgnoreCase);
            s = Regex.Replace(s, @"<\/?o:p>", "", RegexOptions.IgnoreCase);
            s = Regex.Replace(s, @"\[(em\d+)\]", "{/$1}", RegexOptions.IgnoreCase);
            return s;
        }
        #endregion

        #region UBB转换到Html函数
        /// <summary>
        /// 把Ubb转换到html，暂时只能进行简单的转换
        /// </summary>
        /// <returns></returns>
        public static string Ubb2Html(string str)
        {
            str = Regex.Replace(str, @"\[url](?<url>.+?)\[/url]", "<a   href=${url}   target=_blank>${url}</a>", RegexOptions.IgnoreCase);
            str = Regex.Replace(str, @"\[url=(?<url>.+?)](?<name>.+?)\[/url]", "<a   href=${url}   target=_blank>${name}</a>", RegexOptions.IgnoreCase);
            str = Regex.Replace(str, @"\[email](?<email>.+?)\[/email]", "<a   href=mailt${email}   target=_blank>${email}</a>", RegexOptions.IgnoreCase);
            str = Regex.Replace(str, @"\[email=(?<email>.+?)](?<name>.+?)\[/email]", "<a   href=mailt${email}   target=_blank>${name}</a>", RegexOptions.IgnoreCase);
            str = Regex.Replace(str, @"\[flash](?<flash>.+?)\[/flash]", "<div   style=width:640;text-align:left><a   href=${flash}>[\u5168\u5c4f\u67e5\u770b]</a></div><object   codebase=http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=4,0,2,0   classid=clsid:d27cdb6e-ae6d-11cf-96b8-444553540000   width=640   height=480><param   name=movie   value=${flash}><param   name=quality   value=high><embed   src=${flash}   quality=high   pluginspage=http://www.macromedia.com/shockwave/download/index.cgi?p1_prod_version=shockwaveflash   type=application/x-shockwave-flash   width=640   height=480></embed></object>", RegexOptions.IgnoreCase);
            str = Regex.Replace(str, @"\[dir=(?<width>[0-9]+?),(?<height>[0-9]+?)](?<url>.+?)\[/dir]", "<object   classid=clsid:166b1bca-3f9c-11cf-8075-444553540000   codebase=http://download.macromedia.com/pub/shockwave/cabs/director/sw.cab#version=7,0,2,0   width=${width}   height=${height}><param   name=src   value=${url}><embed   src=${url}   pluginspage=http://www.macromedia.com/shockwave/download/   width=${width}   height=${height}></embed></object>", RegexOptions.IgnoreCase);
            str = Regex.Replace(str, @"\[rm=(?<width>[0-9]+?),(?<height>[0-9]+?)](?<url>.+?)\[/rm]", "<object   classid=clsid:cfcdaa03-8be4-11cf-b84b-0020afbbccfa   class=object   id=raocx   width=${width}   height=${height}><param   name=src   value=${url}><param   name=console   value=clip1><param   name=controls   value=imagewindow><param   name=autostart   value=true></object><br><object   classid=clsid:cfcdaa03-8be4-11cf-b84b-0020afbbccfa   height=32   id=video2   width=${width}><param   name=src   value=${url}><param   name=autostart   value=-1><param   name=controls   value=controlpanel><param   name=console   value=clip1></object>", RegexOptions.IgnoreCase);
            str = Regex.Replace(str, @"\[mp=(?<width>[0-9]+?),(?<height>[0-9]+?)](?<url>.+?)\[/mp]", "<object   align=middle   classid=clsid:22d6f312-b0f6-11d0-94ab-0080c74c7e95   class=object   id=mediaplayer   width=${width}   height=${height}   ><param   name=showstatusbar   value=-1><param   name=filename   value=${url}><embed   type=application/x-oleobject   codebase=http://activex.microsoft.com/activex/controls/mplayer/en/nsmp2inf.cab#version=5,1,52,701   flename=mp   src=${url}   width=${width}   height=${height}></embed></object>", RegexOptions.IgnoreCase);
            str = Regex.Replace(str, @"\[qt=(?<width>[0-9]+?),(?<height>[0-9]+?)](?<url>.+?)\[/qt]", "<embed   src=${url}   width=${width}   height=${height}   autoplay=true   loop=false   controller=true   playeveryframe=false   cache=false   scale=tofit   bgcolor=#000000   kioskmode=false   targetcache=false   pluginspage=http://www.apple.com/quicktime/>", RegexOptions.IgnoreCase);
            str = Regex.Replace(str, @"\[img](?<img>.+?)\[/img]", "<a   href=${img}   target=_blank><img   src=${img}   border=0   ></a>", RegexOptions.IgnoreCase);
            str = Regex.Replace(str, @"\[color=(?<color>.+?)](?<text>.+?)\[/color]", "<font   color=${color}>${text}</font>", RegexOptions.IgnoreCase);
            str = Regex.Replace(str, @"\[face=(?<face>.+?)](?<text>.+?)\[/face]", "<font   face=${face}>${text}</font>", RegexOptions.IgnoreCase);
            str = Regex.Replace(str, @"\[down=(?<file>.+?)](?<text>.+?)\[/down]", "<a   href=${file}   target=_blank>${text}</a>", RegexOptions.IgnoreCase);
            str = Regex.Replace(str, @"\[align=(?<align>.+?)](?<text>.+?)\[/align]", "<div   align=${align}>${text}</div>", RegexOptions.IgnoreCase);
            str = Regex.Replace(str, @"\[quote](?<text>.+?)\[/quote]", "<div   class=quote>${text}</div>", RegexOptions.IgnoreCase);
            //str = Regex.Replace(str, @"\(?<text>.+?)\", "<i>${text}</i>", RegexOptions.IgnoreCase);
            str = Regex.Replace(str, @"\[u](?<text>.+?)\[/u]", "<u>${text}</u>", RegexOptions.IgnoreCase);
            //    str = Regex.Replace(str, @"\(?<text>.+?)\", "<b>${text}</b>", RegexOptions.IgnoreCase);
            str = Regex.Replace(str, @"\[size=(?<size>.+?)](?<text>.+?)\[/size]", "<font   size=${size}>${text}</font>", RegexOptions.IgnoreCase);
            str = Regex.Replace(str, @"\[\*](?<text>.+?)\[/\*]", "<li>${text}</li>", RegexOptions.IgnoreCase);
            str = Regex.Replace(str, @"\[list](?<text>.+?)\[/list]", "<ul>${text}</ul>", RegexOptions.IgnoreCase);
            str = Regex.Replace(str, @"\[list=(?<type>.+?)](?<text>.+?)\[/list]", "<ol   type=${type}>${text}</ol   id=${type}>", RegexOptions.IgnoreCase);
            return str;
        }
        #endregion

        #region 检查Url地址函数
        /// <summary>
        /// 检查http
        /// </summary>
        /// <param name="bbsURL"></param>
        /// <returns></returns>
        public static string CheckURL(string bbsURL)
        {
            if (bbsURL != string.Empty && bbsURL.EndsWith(@"/"))
                bbsURL = bbsURL.Remove(bbsURL.Length - 1);
            if (bbsURL.ToLower().IndexOf("localhost") >= 0)
            {
                return bbsURL;
            }

            if (Regex.IsMatch(bbsURL.ToLower(), @"(http://)?([\w-]+\.)+[\w-]+(/[\w- ./?%&=]*)?"))
                return bbsURL;
            else
                return string.Empty;
        }

        #endregion

        #region 数字字符串检查

        /// <summary>
        /// 检查Request查询字符串的键值，是否是数字，最大长度限制
        /// </summary>
        /// <param name="req">Request</param>
        /// <param name="inputKey">Request的键值</param>
        /// <param name="maxLen">最大长度</param>
        /// <returns>返回Request查询字符串</returns>
        public static string FetchInputDigit(System.Web.HttpRequest req, string inputKey, int maxLen)
        {
            string retVal = string.Empty;
            if (inputKey != null && inputKey != string.Empty)
            {
                retVal = req.QueryString[inputKey];
                if (null == retVal)
                    retVal = req.Form[inputKey];
                if (null != retVal)
                {
                    retVal = SqlText(retVal, maxLen);
                    if (!IsNumber(retVal))
                        retVal = string.Empty;
                }
            }
            if (retVal == null)
                retVal = string.Empty;
            return retVal;
        }
        /// <summary>
        /// 是否数字字符串
        /// </summary>
        /// <param name="inputData">输入字符串</param>
        /// <returns></returns>
        public static bool IsNumber(string inputData)
        {
            Match m = RegNumber.Match(inputData);
            return m.Success;
        }
        /// <summary>
        /// 是否数字字符串 可带正负号
        /// </summary>
        /// <param name="inputData">输入字符串</param>
        /// <returns></returns>
        public static bool IsNumberSign(string inputData)
        {
            Match m = RegNumberSign.Match(inputData);
            return m.Success;
        }
        /// <summary>
        /// 是否是浮点数
        /// </summary>
        /// <param name="inputData">输入字符串</param>
        /// <returns></returns>
        public static bool IsDecimal(string inputData)
        {
            Match m = RegDecimal.Match(inputData);
            return m.Success;
        }
        /// <summary>
        /// 是否是浮点数 可带正负号
        /// </summary>
        /// <param name="inputData">输入字符串</param>
        /// <returns></returns>
        public static bool IsDecimalSign(string inputData)
        {
            Match m = RegDecimalSign.Match(inputData);
            return m.Success;
        }

        #endregion

        #region 中文检测

        /// <summary>
        /// 检测是否有中文字符
        /// </summary>
        /// <param name="inputData"></param>
        /// <returns></returns>
        public static bool IsHasCHZN(string inputData)
        {
            Match m = RegCHZN.Match(inputData);
            return m.Success;
        }

        #endregion

        #region 判断是否是邮件地址
        /// <summary>
        /// 是否是Email
        /// </summary>
        /// <param name="inputData">输入字符串</param>
        /// <returns></returns>
        public static bool IsEmail(string inputData)
        {
            Match m = RegEmail.Match(inputData);
            return m.Success;
        }

        #endregion

        #region 判断密码是否符合要求
        /// <summary>
        /// 密码验证（6-16位数字或字母）
        /// </summary>
        /// <param name="inputData"></param>
        /// <returns></returns>
        public static bool IsPwd(string inputData)
        {
            Match m = RegPwd.Match(inputData);
            return m.Success;

        }

        #endregion

        #region 其他

        /// <summary>
        /// 检查字符串最大长度，返回指定长度的串
        /// </summary>
        /// <param name="sqlInput">输入字符串</param>
        /// <param name="maxLength">最大长度</param>
        /// <returns></returns>			
        public static string SqlText(string sqlInput, int maxLength)
        {
            if (sqlInput != null && sqlInput != string.Empty)
            {
                sqlInput = sqlInput.Trim();
                if (sqlInput.Length > maxLength)//按最大长度截取字符串
                    sqlInput = sqlInput.Substring(0, maxLength);
            }
            return sqlInput;
        }


        /// <summary>
        /// 字符串编码
        /// </summary>
        /// <param name="inputData"></param>
        /// <returns></returns>
        public static string HtmlEncode(string inputData)
        {
            return HttpUtility.HtmlEncode(inputData);
        }
        /// <summary>
        /// 设置Label显示Encode的字符串
        /// </summary>
        /// <param name="lbl"></param>
        /// <param name="txtInput"></param>
        public static void SetLabel(Label lbl, string txtInput)
        {
            lbl.Text = HtmlEncode(txtInput);
        }
        public static void SetLabel(Label lbl, object inputObj)
        {
            SetLabel(lbl, inputObj.ToString());
        }

        #endregion

        #region md5加密函数
        /// <summary>
        ///自定义md5加密函数
        /// </summary> 
        public static string md5(string strTemp)
        {

            string strMd5 = null;
            if (strTemp != null)
            {
                strMd5 = FormsAuthentication.HashPasswordForStoringInConfigFile(strTemp, "MD5").ToLower();
            }
            else
            {
                strMd5 = "imiliudao,aryouok?";
            }
            //为避免被破解进行替换混淆
            strMd5 = strMd5.Replace("a", "c").Replace("1", "b");
            return strMd5;
        }

        #endregion

        #region 处理密码 Hash密码 Encrypt(string password)
        /// <summary>
        /// 处理密码 Hash密码
        /// </summary>
        /// <param name="password">Supplied Password</param>
        /// <returns>Encrypted (Hashed) value</returns>
        public static string Encrypt(string password)
        {
            // Force the string to lower case
            //
            password = password.ToLower();

            Byte[] clearBytes = new UnicodeEncoding().GetBytes(password);
            Byte[] hashedBytes = ((HashAlgorithm)CryptoConfig.CreateFromName("MD5")).ComputeHash(clearBytes);

            return BitConverter.ToString(hashedBytes);
        }
        #endregion

        #region 截取长字符串
        /// <summary>
        /// 字符串截取，区分半角
        /// </summary>
        /// <param name="stringToSub">要截取的字符串</param>
        /// <param name="len">截取字符串的长度</param>
        /// <returns>截取后的字符串</returns> 
        public static string cutString(string strInput, int intLen)
        {
            strInput = strInput.Trim();
            byte[] myByte = System.Text.Encoding.Default.GetBytes(strInput);
            if (myByte.Length > intLen)
            {
                //截取操作
                string resultStr = "";
                for (int i = 0; i < strInput.Length; i++)
                {
                    byte[] tempByte = System.Text.Encoding.Default.GetBytes(resultStr);
                    if (tempByte.Length < intLen - 4)
                    {
                        resultStr += strInput.Substring(i, 1);
                    }
                    else
                    {
                        break;
                    }
                }
                return resultStr + "..";
            }
            else
            {
                return strInput;
            }
        } 

        //{
        //    ASCIIEncoding ascii = new ASCIIEncoding();
        //    int tempLen = 0;
        //    string tempString = "";
        //    byte[] s = ascii.GetBytes(stringToSub);
        //    for (int i = 0; i < s.Length; i++)
        //    {
        //        if ((int)s[i] == 63)
        //        {
        //            tempLen += 2;
        //        }
        //        else
        //        {
        //            tempLen += 1;
        //        }

        //        try
        //        {
        //            tempString += stringToSub.Substring(i, 1);
        //        }
        //        catch
        //        {
        //            break;
        //        }

        //        if (tempLen > len)
        //        tempString += "..";
        //            break;
        //    }//end for

        //    //如果截过则加上半个省略号 
        //   // byte[] mybyte = System.Text.Encoding.Default.GetBytes(stringToSub);
        //   // if (tempLen > len)
                

        //    return tempString;

        //}
        #endregion

        #region 替换特殊字符
        /// <summary>
        /// 特殊字符串替换
        /// </summary> 
        public static string repString(string strTemp)
        {
            if (strTemp == null)
                strTemp = "";
            strTemp = strTemp.Replace(" ", "");
            strTemp = strTemp.Replace("*", "");
            strTemp = strTemp.Replace("?", "");
            strTemp = strTemp.Replace("#", "");
            strTemp = strTemp.Replace("@", "");
            strTemp = strTemp.Replace("^", "");
            strTemp = strTemp.Replace("&", "");
            strTemp = strTemp.Replace("+", "");
            strTemp = strTemp.Replace("-", "");
            strTemp = strTemp.Replace("(", "");
            strTemp = strTemp.Replace(")", "");
            strTemp = strTemp.Replace("!", "");
            strTemp = strTemp.Replace("`", "");
            strTemp = strTemp.Replace("~", "");
            strTemp = strTemp.Replace("<", "");
            strTemp = strTemp.Replace(">", "");
            strTemp = strTemp.Replace("'", "");
            strTemp = strTemp.Replace("\"", "");
            strTemp = strTemp.Replace("\\", "");
            strTemp = strTemp.Replace("|", "");
            strTemp = strTemp.Replace("=", "");
            strTemp = strTemp.Replace(",", "");

            return strTemp;
        }
        #endregion

        #region 加密数字ID（由于替换了其中一些特殊字符，所以只能单向加密，存储在数据库中）
        //默认密钥向量
        private static byte[] Keys = { 0x12, 0x34, 0x56, 0x78, 0x90, 0xAB, 0xCD, 0xEF };
        /// <summary>
        /// DES加密数字ID，且总长度控制在16内，替换掉了其中的/+=等特殊字符
        /// </summary>
        /// <param name="encryptString">待加密的ID，应该在七位内</param>
        /// <returns>加密成功返回加密后的字符串，失败返回源串</returns>
        public static string EncryptID(string encryptString)
        {
            try
            {
                byte[] rgbKey = Encoding.UTF8.GetBytes("10486678");
                byte[] rgbIV = Keys;
                byte[] inputByteArray = Encoding.UTF8.GetBytes(encryptString);
                DESCryptoServiceProvider dCSP = new DESCryptoServiceProvider();
                MemoryStream mStream = new MemoryStream();
                CryptoStream cStream = new CryptoStream(mStream, dCSP.CreateEncryptor(rgbKey, rgbIV), CryptoStreamMode.Write);
                cStream.Write(inputByteArray, 0, inputByteArray.Length);
                cStream.FlushFinalBlock();
                
                //随机数，用于替换特殊字符
                Random randomRep=new Random();
                string repStr=randomRep.Next(99).ToString();

                return Convert.ToBase64String(mStream.ToArray()).Replace("=", repStr).Replace("/",repStr).Replace("+",repStr).ToUpper();
            }
            catch
            {
                //把“=”替换为"x"，以免"="造成混淆
                return encryptString;
            }
        #endregion
        }

        #region 处理时间格式的函数
        /// <summary>
        /// 时间转换函数
        /// </summary>
        /// <param name="pDate">要转换的时间</param>
        /// <returns>如果是当天日期则显示为今天，昨日则显示为昨天</returns>
        
        public static string repDate(DateTime pDate)
        {
            TimeSpan TS = DateTime.Now - pDate;
            if (Convert.ToInt32(TS.TotalDays)==0)
                return "<font color=red>今-天</font>";
            else if (Convert.ToInt32(TS.TotalDays)==1)
                return "<font color=green>昨-天</font>";
            else if(Convert.ToInt32(TS.TotalDays)==2)
                return "前-天";
            else
                return pDate.ToString("MM-dd");
        }

        /// <summary>
        /// 时间转换函数(具体到秒)
        /// </summary>
        /// <param name="pTime">要转换的时间</param>
        /// <returns>如果是当天日期则显示为今天，昨日则显示为昨天</returns>

        public static string repTime(DateTime pTime)
        {
            TimeSpan TS = DateTime.Now - pTime;
            if (Convert.ToInt32(TS.TotalDays) == 0)
                return "<font color=red>今-天" + pTime.ToShortTimeString() + "</font>";
            else if (Convert.ToInt32(TS.TotalDays) == 1)
                return "昨-天";
            else
                return pTime.ToString("yy-MM-dd hh:mm:s");
        }


        /// <summary>
        /// 详细显示日期和时间的格
        /// </summary>
        /// <param name="pDateTime">要处理的时间</param>
        /// <param name="dateFormat">时间格式（.net语法）</param>
        /// <returns></returns>
        public static string repDateTime(DateTime pDateTime,string dateFormat)
        {
            TimeSpan TS = DateTime.Now.Subtract(pDateTime);

            //用来判断上午下午
            string partDay="";
            if (pDateTime.Hour > 0 && pDateTime.Hour < 8)
                partDay = "<sup>凌晨</sup>";
            else if (pDateTime.Hour > 7 && pDateTime.Hour < 13)
                partDay = "<sup>上午</sup>";
            else if (pDateTime.Hour > 12 && pDateTime.Hour < 15)
                partDay = "<sup>中午</sup>";
            else if (pDateTime.Hour > 14 && pDateTime.Hour < 19)
                partDay = "<sup>下午</sup>";
            else if (pDateTime.Hour > 19 && pDateTime.Hour < 23)
                partDay = "<sup>晚上</sup>";
            else if (pDateTime.Hour > 22 && pDateTime.Hour < 25)
                partDay = "<sup>深夜</sup>";

            int intMinute=Convert.ToInt32(TS.TotalMinutes);
            int intHour = Convert.ToInt32(TS.TotalHours);
            int intDay = Convert.ToInt32(TS.TotalDays);

            if (intMinute < 5 && intHour == 0)
                return "刚刚";
            else if (intMinute < 60 && intMinute > 4)
                return intMinute.ToString() + "<sup>分钟</sup>前";
            else if (intHour > 1 && intHour < 24)
                return intHour + "<sup>小时</sup>前";
            else if (intDay == 1)

                return "昨天"+partDay;

                // return "昨天";
            else if (intDay == 2)
                return "前天"+partDay;
            else
                return pDateTime.ToString(dateFormat);
        }

        #endregion

        #region 删除html格式
        /// <summary>
        /// 替换html特殊字符
        /// </summary>
        /// <param name="strContent"></param>
        /// <returns></returns>
        public static string repHtml(string strContent)
        {
            strContent = strContent.Replace("&", "&amp");
            strContent = strContent.Replace("´", "´´");
            strContent = strContent.Replace("<", "&lt");
            strContent = strContent.Replace(">", "&gt");
            strContent = strContent.Replace("chr(60)", "&lt");
            strContent = strContent.Replace("chr(37)", "&gt");
            strContent = strContent.Replace("\"", "&quot");
            strContent = strContent.Replace(";", ";");
            strContent = strContent.Replace("\n", "<br />");
            strContent = strContent.Replace(" ", "&nbsp");
            return strContent;
        }

        /// <summary>
        /// 清除html特殊字符
        /// </summary>
        /// <param name="strContent"></param>
        /// <returns></returns>
        public static string clearHtml(string strContent)
        {
            strContent = strContent.Replace("&", "");
            strContent = strContent.Replace("´", "");
            strContent = strContent.Replace("<", "");
            strContent = strContent.Replace(">", "");
            strContent = strContent.Replace("chr(60)", "");
            strContent = strContent.Replace("chr(37)", "");
            strContent = strContent.Replace("\"", "");
            strContent = strContent.Replace(";", "");
            strContent = strContent.Replace("\n", "<br/>");
            strContent = strContent.Replace("\\", "");
            return strContent;
        }
        #endregion

        #region 得到目录的列表
        /// <summary>
        /// 得到目录的列表（最多三层）
        /// </summary>
        /// <param name="sourcepath">目录的物理路径</param>
        /// <returns>目录树列表</returns>
        public static string GetDirTree(string sourcepath)
        {
            string strTemp = "";

            //检索根目录下的文件夹，然后循环（最多三层）

            string currentDir = sourcepath.Replace("/", "\\").Replace(Directory.GetParent(sourcepath).ToString(), "");//当前文件夹名称，包括/字符，也就是enid

            string[] arrTopFolder = Directory.GetDirectories(sourcepath, "*", SearchOption.TopDirectoryOnly);
            string[] arrTopFile = Directory.GetFiles(sourcepath, "*.*", SearchOption.TopDirectoryOnly);

            for (int i = 0; i < arrTopFolder.Length; i++)
            {
                //一级目录
                string topfoldername = arrTopFolder[i].ToString().Replace(sourcepath, "");//取得目录名称
               
                strTemp += "<li> " + topfoldername + "</li>\r\n";

                //开始处理二级目录
                string[] arrSubFolder = Directory.GetDirectories(arrTopFolder[i].ToString(), "*", SearchOption.TopDirectoryOnly);
                string[] arrSubFile = Directory.GetFiles(arrTopFolder[i].ToString(), "*.*", SearchOption.TopDirectoryOnly);

                if (arrSubFolder.Length > 0)//如果有子目录
                {
                    strTemp += "<ul>\r\n";
                    for (int j = 0; j < arrSubFolder.Length; j++)
                    {
                        string subfoldername = arrSubFolder[j].ToString().Replace(sourcepath + topfoldername, "");

                        string strSubDot = "";//代码前省略号
                        for (int x = 0; x < topfoldername.Length; x++)
                            strSubDot += ".";
                        strTemp += "<li> " + strSubDot + subfoldername + "</li>\r\n";

                        //处理三级目录
                        string[] arrThirdFolder = Directory.GetDirectories(arrSubFolder[j].ToString(), "*", SearchOption.TopDirectoryOnly);
                        string[] arrThirdFile = Directory.GetFiles(arrSubFolder[j].ToString(), "*.*", SearchOption.TopDirectoryOnly);

                        if (arrThirdFolder.Length > 0)//如果有子目录
                        {
                            strTemp += "<ul>\r\n";
                            for (int k = 0; k < arrThirdFolder.Length; k++)
                            {
                                string thirdfoldername = arrThirdFolder[k].ToString().Replace(sourcepath + topfoldername, "");
                                string strThirdDot = "";//代码名称前省略号
                                for (int y = 0; y < subfoldername.Length; y++)
                                    strThirdDot += ".";

                                strTemp += "<li> " + strThirdDot + thirdfoldername + "</li>\r\n";

                            }//end for

                            if (arrThirdFile.Length < 1)
                                strTemp += "</ul>\r\n";

                            strTemp += "</u>\r\n";
                        }//end if


                        //开始处理三级文件

                        if (arrThirdFile.Length > 0)
                        {
                            if (arrThirdFolder.Length < 1)
                                strTemp += "<ul>\r\n";
                            for (int m = 0; m < arrThirdFile.Length; m++)
                            {
                                string thirdfilename = arrThirdFile[m].ToString().Replace(sourcepath + topfoldername + subfoldername, "");
                                string strDot = "";//代码前省略号
                                for (int z = 0; z < subfoldername.Length; z++)
                                    strDot += ".";
                                strTemp += "<li> <a href=\"/CV" + currentDir + topfoldername + subfoldername + thirdfilename + ".html\" title=\"点击查看详细信息\" target=\"_blank\">" + strDot + thirdfilename + "</a></li>";

                            }//end for
                            strTemp += "</ul>\r\n";
                        }//end if
                    }//end for
                    //如果无同级文件则显示ul
                    if (arrSubFile.Length < 1)
                        strTemp += "</ul>\r\n";
                }//end if

                //开始处理二级文件

                if (arrSubFile.Length > 0)//判断是否有子文件
                {
                    //如果无同级目录则显示
                    if (arrSubFolder.Length < 1)
                        strTemp += "<ul>\r\n";
                    for (int l = 0; l < arrSubFile.Length; l++)
                    {
                        string subfilename = arrSubFile[l].ToString().Replace(sourcepath + topfoldername, "");
                        string strDot = "";//代码前省略号
                        for (int y = 0; y < topfoldername.Length; y++)
                            strDot += ".";

                        strTemp += "<li> <a href=\"/CV" + currentDir + topfoldername + subfilename + ".html\" title=\"点击查看详细信息\" target=\"_blank\">" +strDot+ subfilename + "</a></li>";

                    }//end for

                    strTemp += "</ul>\r\n";
                }//end if
            }//end for

            //处理一级文件
            for (int i = 0; i < arrTopFile.Length; i++)
            {
                string topfilename = arrTopFile[i].ToString().Replace(sourcepath, "");
                strTemp += "<li> <a href=\"/CV" + currentDir + topfilename + ".html\" title=\"点击查看详细信息\" target=\"_blank\">" + topfilename + "</a></li>";

            }
            //把App_Code替换为App-Code，否则会出现“找不到文件的错误”，读取得时候记得返回
            strTemp = strTemp.Replace("App_Code","App-Code");
            return strTemp;

        }
        #endregion

        /// <summary>
        /// 返回 URL 字符串的编码结果
        /// </summary>
        /// <param name="str">字符串</param>
        /// <returns>编码结果</returns>
        public static string UrlEncode(string str)
        {
            return HttpUtility.UrlEncode(str);
        }

        /// <summary>
        /// 返回 URL 字符串的编码结果
        /// </summary>
        /// <param name="str">字符串</param>
        /// <returns>解码结果</returns>
        public static string UrlDecode(string str)
        {
            return HttpUtility.UrlDecode(str);
        }

        /// <summary>
        /// 以指定的ContentType输出指定文件文件
        /// </summary>
        /// <param name="filepath">文件路径</param>
        /// <param name="filename">输出的文件名</param>
        /// <param name="filetype">将文件输出时设置的ContentType</param>
        public static void ResponseFile(string filepath, string filename, string filetype)
        {
            Stream iStream = null;

            // 缓冲区为10k
            byte[] buffer = new Byte[10000];

            // 文件长度
            int length;

            // 需要读的数据长度
            long dataToRead;

            try
            {
                // 打开文件
                iStream = new FileStream(filepath, FileMode.Open, FileAccess.Read, FileShare.Read);


                // 需要读的数据长度
                dataToRead = iStream.Length;

                HttpContext.Current.Response.ContentType = filetype;
                HttpContext.Current.Response.AddHeader("Content-Disposition", "attachment;filename=" + UrlEncode(filename.Trim()).Replace("+", " "));

                while (dataToRead > 0)
                {
                    // 检查客户端是否还处于连接状态
                    if (HttpContext.Current.Response.IsClientConnected)
                    {
                        length = iStream.Read(buffer, 0, 10000);
                        HttpContext.Current.Response.OutputStream.Write(buffer, 0, length);
                        HttpContext.Current.Response.Flush();
                        buffer = new Byte[10000];
                        dataToRead = dataToRead - length;
                    }
                    else
                    {
                        // 如果不再连接则跳出死循环
                        dataToRead = -1;
                    }
                }
            }
            catch (Exception ex)
            {
                HttpContext.Current.Response.Write("Error : " + ex.Message);
            }
            finally
            {
                if (iStream != null)
                {
                    // 关闭文件
                    iStream.Close();
                }
            }
            HttpContext.Current.Response.End();
        }
    }

}
