//*--------------------------------------
//* Create By Yesun .Net Tool V1.1
//* Email:edzh@tom.com QQ:363980
//* Msn:dyesur@hotmail.com
//* Web http://edzh.com
//* DateTime 2005-02-13
//*--------------------------------------
using System;
using System.Collections;
using System.ComponentModel;
using System.Data;
using System.Web;
using System.Xml;
using System.Xml.Xsl;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;
using System.Text.RegularExpressions;
using System.IO;
using System.Configuration;
using System.Threading;
using System.Text;
using log4net;
using System.Drawing;
using System.Runtime.InteropServices;
using System.Diagnostics;
using System.Reflection;
namespace Yesun.Edzh.Util
{
/**//// <summary>
/// 常用函数 - CommFunction
/// </summary>
public class Utils
{
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-]+\.(com|net|org|edu|mil|tv|biz|info)$");//w 英文字母或数字的字符串,和 [a-zA-Z0-9] 语法一样
private static Regex RegCHZN = new Regex("[\u4e00-\u9fa5]");//中文
private static readonly log4net.ILog log = LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
private static FileVersionInfo AssemblyFileVersion = FileVersionInfo.GetVersionInfo(Assembly.GetExecutingAssembly().Location);
static object lockObject = new object();
Common#region Common
/**//// <summary>
/// 获得当前绝对路径
/// </summary>
/// <param name="strPath">指定的路径</param>
/// <returns>绝对路径</returns>
public static string GetMapPath(string strPath)
{
if (HttpContext.Current != null)
{
return HttpContext.Current.Server.MapPath(strPath);
}
else //非web程序引用
{
return System.IO.Path.Combine(AppDomain.CurrentDomain.BaseDirectory, strPath);
}
}
/**//// <summary>
/// 是否为ip
/// </summary>
/// <param name="ip"></param>
/// <returns></returns>
public static bool IsIP(string ip)
{
return Regex.IsMatch(ip, @"^((2[0-4]\d|25[0-5]|[01]?\d\d?)\.){3}(2[0-4]\d|25[0-5]|[01]?\d\d?)$");
}
public static bool IsIPSect(string ip)
{
return Regex.IsMatch(ip, @"^((2[0-4]\d|25[0-5]|[01]?\d\d?)\.){2}((2[0-4]\d|25[0-5]|[01]?\d\d?|\*)\.)(2[0-4]\d|25[0-5]|[01]?\d\d?|\*)$");
}
/**//// <summary>
/// 获得Assembly版本号
/// </summary>
/// <returns></returns>
public static string GetAssemblyVersion()
{
return string.Format("{0}.{1}.{2}", AssemblyFileVersion.FileMajorPart, AssemblyFileVersion.FileMinorPart, AssemblyFileVersion.FileBuildPart);
}
/**//// <summary>
/// 获得Assembly产品名称
/// </summary>
/// <returns></returns>
public static string GetAssemblyProductName()
{
return AssemblyFileVersion.ProductName;
}
/**//// <summary>
/// 获得Assembly产品版权
/// </summary>
/// <returns></returns>
public static string GetAssemblyCopyright()
{
return AssemblyFileVersion.LegalCopyright;
}
/**//// <summary>
/// 创建目录
/// </summary>
/// <param name="name">名称</param>
/// <returns>创建是否成功</returns>
[DllImport("dbgHelp", SetLastError = true)]
private static extern bool MakeSureDirectoryPathExists(string name);
/**//// <summary>
/// 写cookie值
/// </summary>
/// <param name="strName">名称</param>
/// <param name="strValue">值</param>
public static void WriteCookie(string strName, string strValue)
{
HttpCookie cookie = HttpContext.Current.Request.Cookies[strName];
if (cookie == null)
{
cookie = new HttpCookie(strName);
}
cookie.Value = strValue;
HttpContext.Current.Response.AppendCookie(cookie);
}
/**//// <summary>
/// 写cookie值
/// </summary>
/// <param name="strName">名称</param>
/// <param name="strValue">值</param>
/// <param name="strValue">过期时间(分钟)</param>
public static void WriteCookie(string strName, string strValue, int expires)
{
HttpCookie cookie = HttpContext.Current.Request.Cookies[strName];
if (cookie == null)
{
cookie = new HttpCookie(strName);
}
cookie.Value = strValue;
cookie.Expires = DateTime.Now.AddMinutes(expires);
HttpContext.Current.Response.AppendCookie(cookie);
}
/**//// <summary>
/// 读cookie值
/// </summary>
/// <param name="strName">名称</param>
/// <returns>cookie值</returns>
public static string GetCookie(string strName)
{
if (HttpContext.Current.Request.Cookies != null && HttpContext.Current.Request.Cookies[strName] != null)
{
return HttpContext.Current.Request.Cookies[strName].Value.ToString();
}
return "";
}
/**//// <summary>
/// 得到论坛的真实路径
/// </summary>
/// <returns></returns>
public static string GetTrueForumPath()
{
string forumPath = HttpContext.Current.Request.Path;
if (forumPath.LastIndexOf("/") != forumPath.IndexOf("/"))
{
forumPath = forumPath.Substring(forumPath.IndexOf("/"), forumPath.LastIndexOf("/") + 1);
}
else
{
forumPath = "/";
}
return forumPath;
}
/**//// <summary>
/// 判断字符串是否是yy-mm-dd字符串
/// </summary>
/// <param name="str">待判断字符串</param>
/// <returns>判断结果</returns>
public static bool IsDateString(string str)
{
return Regex.IsMatch(str, @"(\d{4})-(\d{1,2})-(\d{1,2})");
}
/**//// <summary>
/// 移除Html标记
/// </summary>
/// <param name="content"></param>
/// <returns></returns>
public static string RemoveHtml(string content)
{
string regexstr = @"<[^>]*>";
return Regex.Replace(content, regexstr, string.Empty, RegexOptions.IgnoreCase);
}
/**//// <summary>
/// 过滤HTML中的不安全标签
/// </summary>
/// <param name="content"></param>
/// <returns></returns>
public static string RemoveUnsafeHtml(string content)
{
content = Regex.Replace(content, @"(\<|\s+)o([a-z]+\s?=)", "$1$2", RegexOptions.IgnoreCase);
content = Regex.Replace(content, @"(script|frame|form|meta|behavior|style)([\s|:|>])+", "$1.$2", RegexOptions.IgnoreCase);
return content;
}
#endregion
File#region File
/**//// <summary>
/// 创建目录
/// </summary>
/// <param name="path"></param>
public static void CreateDir(string path)
{
if (!Directory.Exists(path))
{
Directory.CreateDirectory(path);
}
}
/**//// <summary>
/// 文件是否存在
/// </summary>
/// <param name="filename"></param>
public static bool FileExists(string filename)
{
return System.IO.File.Exists(filename);
}
#endregion
带时间的GUID#region 带时间的GUID
/**////<summary>
/// 返回 GUID 用于数据库操作,特定的时间代码可以提高检索效率
/// </summary>
/// <returns>COMB (GUID 与时间混合型) 类型 GUID 数据</returns>
public static Guid NewComb()
{
byte[] guidArray = System.Guid.NewGuid().ToByteArray();
DateTime baseDate = new DateTime(1900, 1, 1);
DateTime now = DateTime.Now;
// Get the days and milliseconds which will be used to build the byte string
TimeSpan days = new TimeSpan(now.Ticks - baseDate.Ticks);
TimeSpan msecs = new TimeSpan(now.Ticks - (new DateTime(now.Year, now.Month, now.Day).Ticks));
// Convert to a byte array
// Note that SQL Server is accurate to 1/300th of a millisecond so we divide by 3.333333
byte[] daysArray = BitConverter.GetBytes(days.Days);
byte[] msecsArray = BitConverter.GetBytes((long)(msecs.TotalMilliseconds / 3.333333));
// Reverse the bytes to match SQL Servers ordering
Array.Reverse(daysArray);
Array.Reverse(msecsArray);
// Copy the bytes into the guid
Array.Copy(daysArray, daysArray.Length - 2, guidArray, guidArray.Length - 6, 2);
Array.Copy(msecsArray, msecsArray.Length - 4, guidArray, guidArray.Length - 4, 4);
return new System.Guid(guidArray);
}
/**//// <summary>
/// 从 SQL SERVER 返回的 GUID 中生成时间信息
/// </summary>
/// <param name="guid">包含时间信息的 COMB </param>
/// <returns>时间</returns>
public static DateTime GetDateFromComb(System.Guid guid)
{
DateTime baseDate = new DateTime(1900, 1, 1);
byte[] daysArray = new byte[4];
byte[] msecsArray = new byte[4];
byte[] guidArray = guid.ToByteArray();
// Copy the date parts of the guid to the respective byte arrays.
Array.Copy(guidArray, guidArray.Length - 6, daysArray, 2, 2);
Array.Copy(guidArray, guidArray.Length - 4, msecsArray, 0, 4);
// Reverse the arrays to put them into the appropriate order
Array.Reverse(daysArray);
Array.Reverse(msecsArray);
// Convert the bytes to ints
int days = BitConverter.ToInt32(daysArray, 0);
int msecs = BitConverter.ToInt32(msecsArray, 0);
DateTime date = baseDate.AddDays(days);
date = date.AddMilliseconds(msecs * 3.333333);
return date;
}
#endregion
Hashtable#region Hashtable
/**//// <summary>
/// 通过Key读取Object
/// </summary>
/// <param name="key"></param>
/// <param name="ht"></param>
/// <returns></returns>
public static object GetHashtableValue(string key, Hashtable ht)
{
if (ht.ContainsKey(key))
{
return ht[key];
}
return null;
}
#endregion
permission#region permission
/**//// <summary>
/// 判断是否拥有某项权限
/// </summary>
/// <param name="htPermission">权限列表</param>
/// <param name="permission">某权限</param>
/// <returns></returns>
public static bool CheckPermission(Hashtable ht, string pName, string op)
{
if (ht == null)
return false;
return ht.Contains((object)(pName + op));
}
#endregion
xml/xslt#region xml/xslt
/**//// <summary>
/// xslt解析xml .net2.0
/// </summary>
/// <param name="objXML4XSL">传入的XmlDocument</param>
/// <param name="xslPath">服务器上xsl的绝对地址</param>
/// <returns>返回String 为HTML格式</returns>
public static string XslTransform(XmlDocument objXml, string xslt)
{
XslCompiledTransform objXSL = new XslCompiledTransform();
objXSL.Load(xslt);
XmlWriterSettings settings = new XmlWriterSettings();
StringBuilder sb = new StringBuilder();
settings.Indent = false;
//settings.IndentChars = "\t";
settings.Encoding = new UTF8Encoding(false);
settings.ConformanceLevel = ConformanceLevel.Auto;
/**////settings.OmitXmlDeclaration = false;
XmlWriter writer = XmlWriter.Create(sb, settings);
objXSL.Transform(objXml, null, writer);
return sb.ToString().Replace("xmlns=\"\"", "");
}
#endregion
MD5/safe#region MD5/safe
/**//// <summary>
/// md5加密
/// </summary>
/// <param name="str"></param>
/// <returns></returns>
public static string MD5(string str)
{
return FormsAuthentication.HashPasswordForStoringInConfigFile(str, "md5");
}
#endregion
字符串操作#region 字符串操作
/**//// <summary>
/// 混淆html页面
/// </summary>
/// <param name="content"></param>
/// <returns></returns>
public static string Html2Html(string content, string copyright, string error)
{
error = error.Replace("<", "");
error = error.Replace(">", "");
error = System.Text.Encoding.UTF8.GetString(System.Text.Encoding.Unicode.GetBytes(error));
content = content.Replace("。", "。<span class='hidden'>" + error + copyright + error + "</span>");
return content;
}
/**//// <summary>
/// 把第一个字母转化为大写
/// </summary>
/// <param name="str"></param>
/// <returns></returns>
public static string FirstCharToLower(string str)
{
if(str == "")
return "";
StringBuilder sb = new StringBuilder();
sb.Append(str);
return (sb[0].ToString().ToLower() + sb.ToString().Substring(1));
}
/**//// <summary>
/// 把第一个字母转化为小写
/// </summary>
/// <param name="str"></param>
/// <returns></returns>
public static string FirstCharToUpper(string str)
{
if(str == "")
return "";
StringBuilder sb = new StringBuilder();
sb.Append(str);
return (sb[0].ToString().ToUpper() + sb.ToString().Substring(1));
}
/**//// <summary>
/// 返回一个六位随机数(验证码).
/// </summary>
public static string GenerateRandomCode()
{
Random random = new Random();
string s = "";
for (int i = 0; i < 6; i++)
s = String.Concat(s, random.Next(10).ToString());
return s;
}
/**//// <summary>
/// 替换文章标题的半角字符
/// </summary>
/// <param name="strInput">输入string</param>
/// <returns></returns>
public static string ReplaceSpecialChar(string strInput)
{
string temp = strInput;
//标点符号替换开始
temp = temp.Replace(" "," ");
temp = temp.Replace(" "," ");
temp = temp.Replace(" "," ");
temp = temp.Replace("~","~");
temp = temp.Replace("!","!");
temp = temp.Replace("#","#");
temp = temp.Replace("$","¥");
temp = temp.Replace("%","%");
temp = temp.Replace("^","…");
temp = temp.Replace("&","※");
temp = temp.Replace("*","×");
temp = temp.Replace("(","(");
temp = temp.Replace(")",")");
temp = temp.Replace("-","-");
temp = temp.Replace("_","—");
temp = temp.Replace("+","+");
temp = temp.Replace("=","=");
temp = temp.Replace("[","【");
temp = temp.Replace("]","】");
temp = temp.Replace("{","『");
temp = temp.Replace("}","』");
temp = temp.Replace("\\","÷");
temp = temp.Replace("|","§");
temp = temp.Replace(";",";");
temp = temp.Replace("\"","“");
temp = temp.Replace("'","‘");
temp = temp.Replace(",",",");
temp = temp.Replace("<","《");
temp = temp.Replace(">","》");
temp = temp.Replace("<","<");
temp = temp.Replace(">",">");
return temp;
}
/**//// <summary>
/// 替换文章标题的半角字符
/// </summary>
/// <param name="strInput"></param>
/// <returns></returns>
public static string ReplaceSpecialCharAll(string strInput)
{
string temp = strInput;
//标点符号替换开始
temp = temp.Replace(" "," ");
temp = temp.Replace(" "," ");
temp = temp.Replace(" "," ");
temp = temp.Replace("`","·");
temp = temp.Replace("~","~");
temp = temp.Replace("!","!");
temp = temp.Replace("@","◎");
temp = temp.Replace("#","#");
temp = temp.Replace("$","¥");
temp = temp.Replace("%","%");
temp = temp.Replace("^","…");
temp = temp.Replace("&","※");
temp = temp.Replace("*","×");
temp = temp.Replace("(","(");
temp = temp.Replace(")",")");
temp = temp.Replace("-","-");
temp = temp.Replace("_","—");
temp = temp.Replace("+","+");
temp = temp.Replace("=","=");
temp = temp.Replace("[","【");
temp = temp.Replace("]","】");
temp = temp.Replace("{","『");
temp = temp.Replace("}","』");
temp = temp.Replace("\\","÷");
temp = temp.Replace("|","§");
temp = temp.Replace(":",":");
temp = temp.Replace(";",";");
temp = temp.Replace("\"","“");
temp = temp.Replace("'","‘");
temp = temp.Replace(",",",");
temp = temp.Replace(".","。");
temp = temp.Replace("<","《");
temp = temp.Replace(">","》");
temp = temp.Replace("/","/");
temp = temp.Replace("?","?");
temp = temp.Replace("1","1");
temp = temp.Replace("2","2");
temp = temp.Replace("3","3");
temp = temp.Replace("4","4");
temp = temp.Replace("5","5");
temp = temp.Replace("6","6");
temp = temp.Replace("7","7");
temp = temp.Replace("8","8");
temp = temp.Replace("9","9");
temp = temp.Replace("0","0");
temp = temp.Replace("a","a");
temp = temp.Replace("b","b");
temp = temp.Replace("c","c");
temp = temp.Replace("d","d");
temp = temp.Replace("e","e");
temp = temp.Replace("f","f");
temp = temp.Replace("g","g");
temp = temp.Replace("h","h");
temp = temp.Replace("i","i");
temp = temp.Replace("j","j");
temp = temp.Replace("k","k");
temp = temp.Replace("l","l");
temp = temp.Replace("m","m");
temp = temp.Replace("n","n");
temp = temp.Replace("o","o");
temp = temp.Replace("p","p");
temp = temp.Replace("q","q");
temp = temp.Replace("r","r");
temp = temp.Replace("s","s");
temp = temp.Replace("t","t");
temp = temp.Replace("u","u");
temp = temp.Replace("v","v");
temp = temp.Replace("w","w");
temp = temp.Replace("x","x");
temp = temp.Replace("y","y");
temp = temp.Replace("z","z");
temp = temp.Replace("A","A");
temp = temp.Replace("B","B");
temp = temp.Replace("C","C");
temp = temp.Replace("D","D");
temp = temp.Replace("E","E");
temp = temp.Replace("F","F");
temp = temp.Replace("G","G");
temp = temp.Replace("H","H");
temp = temp.Replace("I","I");
temp = temp.Replace("J","J");
temp = temp.Replace("K","K");
temp = temp.Replace("L","L");
temp = temp.Replace("M","M");
temp = temp.Replace("N","N");
temp = temp.Replace("O","O");
temp = temp.Replace("P","P");
temp = temp.Replace("Q","Q");
temp = temp.Replace("R","R");
temp = temp.Replace("S","S");
temp = temp.Replace("T","T");
temp = temp.Replace("U","U");
temp = temp.Replace("V","V");
temp = temp.Replace("W","W");
temp = temp.Replace("X","X");
temp = temp.Replace("Y","Y");
temp = temp.Replace("Z","Z");
return temp;
}
/**//// <summary>
/// 验证字符串是不是日期格式,因为日期有很多格式,用上面的正则表达式就不如这个方便;
/// </summary>
/// <param name="DatStr">需要判断的字符</param>
/// <returns>结果</returns>
/// <permission cref="System.Security.PermissionSet">private</permission>
private static bool IsDateTime(string DatStr)
{
try
{
Convert.ToDateTime(DatStr) ;
return true ;
}
catch(Exception )
{
return false;
}
}
/**//// <summary>
/// 删除最后一个字符
/// </summary>
/// <param name="str"></param>
/// <returns></returns>
public static string RemoveLastChar(string str)
{
if (str == "")
return "";
else
return str.Substring(0, str.Length - 1);
}
/**//// <summary>
/// 将字符串转换为Color
/// </summary>
/// <param name="color"></param>
/// <returns></returns>
public static Color ToColor(string color)
{
int red, green, blue = 0;
char[] rgb;
color = color.TrimStart('#');
color = Regex.Replace(color.ToLower(), "[g-zG-Z]", "");
switch (color.Length)
{
case 3:
rgb = color.ToCharArray();
red = Convert.ToInt32(rgb[0].ToString() + rgb[0].ToString(), 16);
green = Convert.ToInt32(rgb[1].ToString() + rgb[1].ToString(), 16);
blue = Convert.ToInt32(rgb[2].ToString() + rgb[2].ToString(), 16);
return Color.FromArgb(red, green, blue);
case 6:
rgb = color.ToCharArray();
red = Convert.ToInt32(rgb[0].ToString() + rgb[1].ToString(), 16);
green = Convert.ToInt32(rgb[2].ToString() + rgb[3].ToString(), 16);
blue = Convert.ToInt32(rgb[4].ToString() + rgb[5].ToString(), 16);
return Color.FromArgb(red, green, blue);
default:
return Color.FromName(color);
}
}
/**//// <summary>
/// 将全角数字转换为数字
/// </summary>
/// <param name="SBCCase"></param>
/// <returns></returns>
public static string SBCCaseToNumberic(string SBCCase)
{
char[] c = SBCCase.ToCharArray();
for (int i = 0; i < c.Length; i++)
{
byte[] b = System.Text.Encoding.Unicode.GetBytes(c, i, 1);
if (b.Length == 2)
{
if (b[1] == 255)
{
b[0] = (byte)(b[0] + 32);
b[1] = 0;
c[i] = System.Text.Encoding.Unicode.GetChars(b)[0];
}
}
}
return new string(c);
}
#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(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>
/// 是否是浮点数 可带正负号
/// </summary>
/// <param name="inputData">输入字符串</param>
/// <returns></returns>
public static bool IsEmail(string inputData)
{
Match m = RegEmail.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 消息提示对话框
/**//// <summary>
/// 显示消息提示对话框
/// </summary>
/// <param name="page">当前页面指针,一般为this</param>
/// <param name="msg">提示信息</param>
public static void Show(System.Web.UI.Page page,string msg)
{
Type cstype = page.GetType();
ClientScriptManager clientScript = page.ClientScript;
clientScript.RegisterStartupScript(cstype,"message", "<script language='javascript' defer>alert('" + msg.ToString() + "');</script>");
}
/**//// <summary>
/// 控件点击 消息确认提示框
/// </summary>
/// <param name="page">当前页面指针,一般为this</param>
/// <param name="msg">提示信息</param>
public static void ShowConfirm(System.Web.UI.WebControls.WebControl Control,string msg)
{
//Control.Attributes.Add("onClick","if (!window.confirm('"+msg+"')){return false;}");
Control.Attributes.Add("onclick", "return confirm('" + msg + "');") ;
}
/**//// <summary>
/// 显示消息提示对话框,并进行页面跳转
/// </summary>
/// <param name="page">当前页面指针,一般为this</param>
/// <param name="msg">提示信息</param>
/// <param name="url">跳转的目标URL</param>
public static void ShowAndRedirect(System.Web.UI.Page page,string msg,string url)
{
System.Text.StringBuilder Builder=new System.Text.StringBuilder();
Builder.Append("<script language='javascript' defer>");
Builder.AppendFormat("alert('{0}');",msg);
Builder.AppendFormat("top.location.href='{0}'",url);
Builder.Append("</script>");
Type cstype = page.GetType();
ClientScriptManager clientScript = page.ClientScript;
clientScript.RegisterStartupScript(cstype, "message", Builder.ToString());
}
/**//// <summary>
/// 输出自定义脚本信息
/// </summary>
/// <param name="page">当前页面指针,一般为this</param>
/// <param name="script">输出脚本</param>
public static void ResponseScript(System.Web.UI.Page page,string script)
{
Type cstype = page.GetType();
ClientScriptManager clientScript = page.ClientScript;
clientScript.RegisterStartupScript(cstype, "message", "<script language='javascript' defer>" + script + "</script>");
}
/**//// <summary>
/// 正文分页 - FIXME 最好用dom处理分页
/// </summary>
/// <param name="content">文章内容</param>
/// <param name="currentPageId">当前页码</param>
/// <param name="perPageLength">每页字数</param>
/// <returns></returns>
public static string ContentSplitPage(string content, int pageid, int pageLength)
{
int totalPageCount = 1;
if (content.Length > pageLength)
{
totalPageCount = (int)Math.Ceiling((double)(content.Length / pageLength));
}
if (pageid > totalPageCount)
{
pageid = totalPageCount;
}
StringBuilder sb = new StringBuilder();
string currentContent = string.Empty;
if (pageid == totalPageCount)
{
currentContent = content.Substring(pageLength * (pageid - 1)) + "<br/>";
}
else
{
currentContent = content.Substring(pageLength * (pageid - 1), pageLength) + "<br/>";
}
//开始对内容进行过滤,防治首位<tag>被拆分
if (currentContent.IndexOf("<") > -1)
{
}
return currentContent;
}
/**//// <summary>
/// 新版分页,但是还是有BUG,当第n页和第n+1页都落在一个标签里时,就有问题,但是事实上不可能!! :)
/// </summary>
/// <param name="content"></param>
/// <param name="pageid"></param>
/// <param name="pageLength"></param>
/// <returns></returns>
public static string ContentSplitPageByXml(string content, int pageid, int pageLength)
{
XmlDataDocument doc = new XmlDataDocument();
doc.LoadXml("<msc>" + content + "</msc>");
//大内容分页
int startIndex = (pageid - 1) * pageLength;
int endIndex = pageid * pageLength;
int index = 0;
XmlNodeList list = doc.FirstChild.ChildNodes;
bool isOK = false;
foreach (XmlNode node in list)
{
if (node.NodeType == XmlNodeType.Element)
{
int nodeLength = node.OuterXml.Length;
if (startIndex > index && startIndex < (index + nodeLength))
{
if (isOK == false)
{
startIndex = index + nodeLength;
isOK = true;
}
}
if (endIndex >= index && endIndex < (index + nodeLength))
{
endIndex = index + nodeLength;
if (endIndex > startIndex)
break;
}
index += nodeLength;
}
else if (node.NodeType == XmlNodeType.Text)
{
int nodeLength = node.InnerText.Length;
if (endIndex >= index && endIndex < (index + nodeLength))
{
if (endIndex > startIndex)
break;
}
index += nodeLength;
}
}
string body = doc.OuterXml;
body = body.Substring(5, body.Length - 11);
int bodyLength = body.Length;
if (endIndex > bodyLength)
{
endIndex = bodyLength;
}
body = body.Substring(startIndex, endIndex - startIndex);
return body;
}
/**//// <summary>
/// 数字转换
/// </summary>
/// <param name="num"></param>
/// <returns></returns>
public static string TransferDayOfWeek(int num)
{
string returnString = "";
switch (num)
{
case 1:
returnString = "一";
break;
case 2:
returnString = "二";
break;
case 3:
returnString = "三";
break;
case 4:
returnString = "四";
break;
case 5:
returnString = "五";
break;
case 6:
returnString = "六";
break;
case 0:
returnString = "日";
break;
}
return returnString;
}
#endregion
backup/restore file#region backup/restore file
/**//// <summary>
/// 备份文件
/// </summary>
/// <param name="sourceFileName">源文件名</param>
/// <param name="destFileName">目标文件名</param>
/// <param name="overwrite">当目标文件存在时是否覆盖</param>
/// <returns>操作是否成功</returns>
public static bool BackupFile(string sourceFileName, string destFileName, bool overwrite)
{
if (!System.IO.File.Exists(sourceFileName))
{
throw new FileNotFoundException(sourceFileName + "文件不存在!");
}
if (!overwrite && System.IO.File.Exists(destFileName))
{
return false;
}
try
{
System.IO.File.Copy(sourceFileName, destFileName, true);
return true;
}
catch (Exception e)
{
throw e;
}
}
/**//// <summary>
/// 备份文件,当目标文件存在时覆盖
/// </summary>
/// <param name="sourceFileName">源文件名</param>
/// <param name="destFileName">目标文件名</param>
/// <returns>操作是否成功</returns>
public static bool BackupFile(string sourceFileName, string destFileName)
{
return BackupFile(sourceFileName, destFileName, true);
}
/**//// <summary>
/// 恢复文件
/// </summary>
/// <param name="backupFileName">备份文件名</param>
/// <param name="targetFileName">要恢复的文件名</param>
/// <param name="backupTargetFileName">要恢复文件再次备份的名称,如果为null,则不再备份恢复文件</param>
/// <returns>操作是否成功</returns>
public static bool RestoreFile(string backupFileName, string targetFileName, string backupTargetFileName)
{
try
{
if (!System.IO.File.Exists(backupFileName))
{
throw new FileNotFoundException(backupFileName + "文件不存在!");
}
if (backupTargetFileName != null)
{
if (!System.IO.File.Exists(targetFileName))
{
throw new FileNotFoundException(targetFileName + "文件不存在!无法备份此文件!");
}
else
{
System.IO.File.Copy(targetFileName, backupTargetFileName, true);
}
}
System.IO.File.Delete(targetFileName);
System.IO.File.Copy(backupFileName, targetFileName);
}
catch (Exception e)
{
throw e;
}
return true;
}
public static bool RestoreFile(string backupFileName, string targetFileName)
{
return RestoreFile(backupFileName, targetFileName, null);
}
#endregion
PageBar#region PageBar
/**//// <summary>
/// 读取页面载入时间
/// </summary>
public static string GetPageProcessTime()
{
lock (lockObject)
{
TimeSpan ts = DateTime.Now - Convert.ToDateTime(HttpContext.Current.Items["AppBeginRequestTime"]);
return "<p class='ar fs10'>页面载入时间:<span class='red'>" + ts.TotalSeconds + "</span>秒 </p>";
}
}
#endregion
}
}
//* Create By Yesun .Net Tool V1.1
//* Email:edzh@tom.com QQ:363980
//* Msn:dyesur@hotmail.com
//* Web http://edzh.com
//* DateTime 2005-02-13
//*--------------------------------------
using System;
using System.Collections;
using System.ComponentModel;
using System.Data;
using System.Web;
using System.Xml;
using System.Xml.Xsl;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;
using System.Text.RegularExpressions;
using System.IO;
using System.Configuration;
using System.Threading;
using System.Text;
using log4net;
using System.Drawing;
using System.Runtime.InteropServices;
using System.Diagnostics;
using System.Reflection;
namespace Yesun.Edzh.Util
{
/**//// <summary>
/// 常用函数 - CommFunction
/// </summary>
public class Utils
{
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-]+\.(com|net|org|edu|mil|tv|biz|info)$");//w 英文字母或数字的字符串,和 [a-zA-Z0-9] 语法一样
private static Regex RegCHZN = new Regex("[\u4e00-\u9fa5]");//中文
private static readonly log4net.ILog log = LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
private static FileVersionInfo AssemblyFileVersion = FileVersionInfo.GetVersionInfo(Assembly.GetExecutingAssembly().Location);
static object lockObject = new object();
Common#region Common
/**//// <summary>
/// 获得当前绝对路径
/// </summary>
/// <param name="strPath">指定的路径</param>
/// <returns>绝对路径</returns>
public static string GetMapPath(string strPath)
{
if (HttpContext.Current != null)
{
return HttpContext.Current.Server.MapPath(strPath);
}
else //非web程序引用
{
return System.IO.Path.Combine(AppDomain.CurrentDomain.BaseDirectory, strPath);
}
}
/**//// <summary>
/// 是否为ip
/// </summary>
/// <param name="ip"></param>
/// <returns></returns>
public static bool IsIP(string ip)
{
return Regex.IsMatch(ip, @"^((2[0-4]\d|25[0-5]|[01]?\d\d?)\.){3}(2[0-4]\d|25[0-5]|[01]?\d\d?)$");
}
public static bool IsIPSect(string ip)
{
return Regex.IsMatch(ip, @"^((2[0-4]\d|25[0-5]|[01]?\d\d?)\.){2}((2[0-4]\d|25[0-5]|[01]?\d\d?|\*)\.)(2[0-4]\d|25[0-5]|[01]?\d\d?|\*)$");
}
/**//// <summary>
/// 获得Assembly版本号
/// </summary>
/// <returns></returns>
public static string GetAssemblyVersion()
{
return string.Format("{0}.{1}.{2}", AssemblyFileVersion.FileMajorPart, AssemblyFileVersion.FileMinorPart, AssemblyFileVersion.FileBuildPart);
}
/**//// <summary>
/// 获得Assembly产品名称
/// </summary>
/// <returns></returns>
public static string GetAssemblyProductName()
{
return AssemblyFileVersion.ProductName;
}
/**//// <summary>
/// 获得Assembly产品版权
/// </summary>
/// <returns></returns>
public static string GetAssemblyCopyright()
{
return AssemblyFileVersion.LegalCopyright;
}
/**//// <summary>
/// 创建目录
/// </summary>
/// <param name="name">名称</param>
/// <returns>创建是否成功</returns>
[DllImport("dbgHelp", SetLastError = true)]
private static extern bool MakeSureDirectoryPathExists(string name);
/**//// <summary>
/// 写cookie值
/// </summary>
/// <param name="strName">名称</param>
/// <param name="strValue">值</param>
public static void WriteCookie(string strName, string strValue)
{
HttpCookie cookie = HttpContext.Current.Request.Cookies[strName];
if (cookie == null)
{
cookie = new HttpCookie(strName);
}
cookie.Value = strValue;
HttpContext.Current.Response.AppendCookie(cookie);
}
/**//// <summary>
/// 写cookie值
/// </summary>
/// <param name="strName">名称</param>
/// <param name="strValue">值</param>
/// <param name="strValue">过期时间(分钟)</param>
public static void WriteCookie(string strName, string strValue, int expires)
{
HttpCookie cookie = HttpContext.Current.Request.Cookies[strName];
if (cookie == null)
{
cookie = new HttpCookie(strName);
}
cookie.Value = strValue;
cookie.Expires = DateTime.Now.AddMinutes(expires);
HttpContext.Current.Response.AppendCookie(cookie);
}
/**//// <summary>
/// 读cookie值
/// </summary>
/// <param name="strName">名称</param>
/// <returns>cookie值</returns>
public static string GetCookie(string strName)
{
if (HttpContext.Current.Request.Cookies != null && HttpContext.Current.Request.Cookies[strName] != null)
{
return HttpContext.Current.Request.Cookies[strName].Value.ToString();
}
return "";
}
/**//// <summary>
/// 得到论坛的真实路径
/// </summary>
/// <returns></returns>
public static string GetTrueForumPath()
{
string forumPath = HttpContext.Current.Request.Path;
if (forumPath.LastIndexOf("/") != forumPath.IndexOf("/"))
{
forumPath = forumPath.Substring(forumPath.IndexOf("/"), forumPath.LastIndexOf("/") + 1);
}
else
{
forumPath = "/";
}
return forumPath;
}
/**//// <summary>
/// 判断字符串是否是yy-mm-dd字符串
/// </summary>
/// <param name="str">待判断字符串</param>
/// <returns>判断结果</returns>
public static bool IsDateString(string str)
{
return Regex.IsMatch(str, @"(\d{4})-(\d{1,2})-(\d{1,2})");
}
/**//// <summary>
/// 移除Html标记
/// </summary>
/// <param name="content"></param>
/// <returns></returns>
public static string RemoveHtml(string content)
{
string regexstr = @"<[^>]*>";
return Regex.Replace(content, regexstr, string.Empty, RegexOptions.IgnoreCase);
}
/**//// <summary>
/// 过滤HTML中的不安全标签
/// </summary>
/// <param name="content"></param>
/// <returns></returns>
public static string RemoveUnsafeHtml(string content)
{
content = Regex.Replace(content, @"(\<|\s+)o([a-z]+\s?=)", "$1$2", RegexOptions.IgnoreCase);
content = Regex.Replace(content, @"(script|frame|form|meta|behavior|style)([\s|:|>])+", "$1.$2", RegexOptions.IgnoreCase);
return content;
}
#endregion
File#region File
/**//// <summary>
/// 创建目录
/// </summary>
/// <param name="path"></param>
public static void CreateDir(string path)
{
if (!Directory.Exists(path))
{
Directory.CreateDirectory(path);
}
}
/**//// <summary>
/// 文件是否存在
/// </summary>
/// <param name="filename"></param>
public static bool FileExists(string filename)
{
return System.IO.File.Exists(filename);
}
#endregion
带时间的GUID#region 带时间的GUID
/**////<summary>
/// 返回 GUID 用于数据库操作,特定的时间代码可以提高检索效率
/// </summary>
/// <returns>COMB (GUID 与时间混合型) 类型 GUID 数据</returns>
public static Guid NewComb()
{
byte[] guidArray = System.Guid.NewGuid().ToByteArray();
DateTime baseDate = new DateTime(1900, 1, 1);
DateTime now = DateTime.Now;
// Get the days and milliseconds which will be used to build the byte string
TimeSpan days = new TimeSpan(now.Ticks - baseDate.Ticks);
TimeSpan msecs = new TimeSpan(now.Ticks - (new DateTime(now.Year, now.Month, now.Day).Ticks));
// Convert to a byte array
// Note that SQL Server is accurate to 1/300th of a millisecond so we divide by 3.333333
byte[] daysArray = BitConverter.GetBytes(days.Days);
byte[] msecsArray = BitConverter.GetBytes((long)(msecs.TotalMilliseconds / 3.333333));
// Reverse the bytes to match SQL Servers ordering
Array.Reverse(daysArray);
Array.Reverse(msecsArray);
// Copy the bytes into the guid
Array.Copy(daysArray, daysArray.Length - 2, guidArray, guidArray.Length - 6, 2);
Array.Copy(msecsArray, msecsArray.Length - 4, guidArray, guidArray.Length - 4, 4);
return new System.Guid(guidArray);
}
/**//// <summary>
/// 从 SQL SERVER 返回的 GUID 中生成时间信息
/// </summary>
/// <param name="guid">包含时间信息的 COMB </param>
/// <returns>时间</returns>
public static DateTime GetDateFromComb(System.Guid guid)
{
DateTime baseDate = new DateTime(1900, 1, 1);
byte[] daysArray = new byte[4];
byte[] msecsArray = new byte[4];
byte[] guidArray = guid.ToByteArray();
// Copy the date parts of the guid to the respective byte arrays.
Array.Copy(guidArray, guidArray.Length - 6, daysArray, 2, 2);
Array.Copy(guidArray, guidArray.Length - 4, msecsArray, 0, 4);
// Reverse the arrays to put them into the appropriate order
Array.Reverse(daysArray);
Array.Reverse(msecsArray);
// Convert the bytes to ints
int days = BitConverter.ToInt32(daysArray, 0);
int msecs = BitConverter.ToInt32(msecsArray, 0);
DateTime date = baseDate.AddDays(days);
date = date.AddMilliseconds(msecs * 3.333333);
return date;
}
#endregion
Hashtable#region Hashtable
/**//// <summary>
/// 通过Key读取Object
/// </summary>
/// <param name="key"></param>
/// <param name="ht"></param>
/// <returns></returns>
public static object GetHashtableValue(string key, Hashtable ht)
{
if (ht.ContainsKey(key))
{
return ht[key];
}
return null;
}
#endregion
permission#region permission
/**//// <summary>
/// 判断是否拥有某项权限
/// </summary>
/// <param name="htPermission">权限列表</param>
/// <param name="permission">某权限</param>
/// <returns></returns>
public static bool CheckPermission(Hashtable ht, string pName, string op)
{
if (ht == null)
return false;
return ht.Contains((object)(pName + op));
}
#endregion
xml/xslt#region xml/xslt
/**//// <summary>
/// xslt解析xml .net2.0
/// </summary>
/// <param name="objXML4XSL">传入的XmlDocument</param>
/// <param name="xslPath">服务器上xsl的绝对地址</param>
/// <returns>返回String 为HTML格式</returns>
public static string XslTransform(XmlDocument objXml, string xslt)
{
XslCompiledTransform objXSL = new XslCompiledTransform();
objXSL.Load(xslt);
XmlWriterSettings settings = new XmlWriterSettings();
StringBuilder sb = new StringBuilder();
settings.Indent = false;
//settings.IndentChars = "\t";
settings.Encoding = new UTF8Encoding(false);
settings.ConformanceLevel = ConformanceLevel.Auto;
/**////settings.OmitXmlDeclaration = false;
XmlWriter writer = XmlWriter.Create(sb, settings);
objXSL.Transform(objXml, null, writer);
return sb.ToString().Replace("xmlns=\"\"", "");
}
#endregion
MD5/safe#region MD5/safe
/**//// <summary>
/// md5加密
/// </summary>
/// <param name="str"></param>
/// <returns></returns>
public static string MD5(string str)
{
return FormsAuthentication.HashPasswordForStoringInConfigFile(str, "md5");
}
#endregion
字符串操作#region 字符串操作
/**//// <summary>
/// 混淆html页面
/// </summary>
/// <param name="content"></param>
/// <returns></returns>
public static string Html2Html(string content, string copyright, string error)
{
error = error.Replace("<", "");
error = error.Replace(">", "");
error = System.Text.Encoding.UTF8.GetString(System.Text.Encoding.Unicode.GetBytes(error));
content = content.Replace("。", "。<span class='hidden'>" + error + copyright + error + "</span>");
return content;
}
/**//// <summary>
/// 把第一个字母转化为大写
/// </summary>
/// <param name="str"></param>
/// <returns></returns>
public static string FirstCharToLower(string str)
{
if(str == "")
return "";
StringBuilder sb = new StringBuilder();
sb.Append(str);
return (sb[0].ToString().ToLower() + sb.ToString().Substring(1));
}
/**//// <summary>
/// 把第一个字母转化为小写
/// </summary>
/// <param name="str"></param>
/// <returns></returns>
public static string FirstCharToUpper(string str)
{
if(str == "")
return "";
StringBuilder sb = new StringBuilder();
sb.Append(str);
return (sb[0].ToString().ToUpper() + sb.ToString().Substring(1));
}
/**//// <summary>
/// 返回一个六位随机数(验证码).
/// </summary>
public static string GenerateRandomCode()
{
Random random = new Random();
string s = "";
for (int i = 0; i < 6; i++)
s = String.Concat(s, random.Next(10).ToString());
return s;
}
/**//// <summary>
/// 替换文章标题的半角字符
/// </summary>
/// <param name="strInput">输入string</param>
/// <returns></returns>
public static string ReplaceSpecialChar(string strInput)
{
string temp = strInput;
//标点符号替换开始
temp = temp.Replace(" "," ");
temp = temp.Replace(" "," ");
temp = temp.Replace(" "," ");
temp = temp.Replace("~","~");
temp = temp.Replace("!","!");
temp = temp.Replace("#","#");
temp = temp.Replace("$","¥");
temp = temp.Replace("%","%");
temp = temp.Replace("^","…");
temp = temp.Replace("&","※");
temp = temp.Replace("*","×");
temp = temp.Replace("(","(");
temp = temp.Replace(")",")");
temp = temp.Replace("-","-");
temp = temp.Replace("_","—");
temp = temp.Replace("+","+");
temp = temp.Replace("=","=");
temp = temp.Replace("[","【");
temp = temp.Replace("]","】");
temp = temp.Replace("{","『");
temp = temp.Replace("}","』");
temp = temp.Replace("\\","÷");
temp = temp.Replace("|","§");
temp = temp.Replace(";",";");
temp = temp.Replace("\"","“");
temp = temp.Replace("'","‘");
temp = temp.Replace(",",",");
temp = temp.Replace("<","《");
temp = temp.Replace(">","》");
temp = temp.Replace("<","<");
temp = temp.Replace(">",">");
return temp;
}
/**//// <summary>
/// 替换文章标题的半角字符
/// </summary>
/// <param name="strInput"></param>
/// <returns></returns>
public static string ReplaceSpecialCharAll(string strInput)
{
string temp = strInput;
//标点符号替换开始
temp = temp.Replace(" "," ");
temp = temp.Replace(" "," ");
temp = temp.Replace(" "," ");
temp = temp.Replace("`","·");
temp = temp.Replace("~","~");
temp = temp.Replace("!","!");
temp = temp.Replace("@","◎");
temp = temp.Replace("#","#");
temp = temp.Replace("$","¥");
temp = temp.Replace("%","%");
temp = temp.Replace("^","…");
temp = temp.Replace("&","※");
temp = temp.Replace("*","×");
temp = temp.Replace("(","(");
temp = temp.Replace(")",")");
temp = temp.Replace("-","-");
temp = temp.Replace("_","—");
temp = temp.Replace("+","+");
temp = temp.Replace("=","=");
temp = temp.Replace("[","【");
temp = temp.Replace("]","】");
temp = temp.Replace("{","『");
temp = temp.Replace("}","』");
temp = temp.Replace("\\","÷");
temp = temp.Replace("|","§");
temp = temp.Replace(":",":");
temp = temp.Replace(";",";");
temp = temp.Replace("\"","“");
temp = temp.Replace("'","‘");
temp = temp.Replace(",",",");
temp = temp.Replace(".","。");
temp = temp.Replace("<","《");
temp = temp.Replace(">","》");
temp = temp.Replace("/","/");
temp = temp.Replace("?","?");
temp = temp.Replace("1","1");
temp = temp.Replace("2","2");
temp = temp.Replace("3","3");
temp = temp.Replace("4","4");
temp = temp.Replace("5","5");
temp = temp.Replace("6","6");
temp = temp.Replace("7","7");
temp = temp.Replace("8","8");
temp = temp.Replace("9","9");
temp = temp.Replace("0","0");
temp = temp.Replace("a","a");
temp = temp.Replace("b","b");
temp = temp.Replace("c","c");
temp = temp.Replace("d","d");
temp = temp.Replace("e","e");
temp = temp.Replace("f","f");
temp = temp.Replace("g","g");
temp = temp.Replace("h","h");
temp = temp.Replace("i","i");
temp = temp.Replace("j","j");
temp = temp.Replace("k","k");
temp = temp.Replace("l","l");
temp = temp.Replace("m","m");
temp = temp.Replace("n","n");
temp = temp.Replace("o","o");
temp = temp.Replace("p","p");
temp = temp.Replace("q","q");
temp = temp.Replace("r","r");
temp = temp.Replace("s","s");
temp = temp.Replace("t","t");
temp = temp.Replace("u","u");
temp = temp.Replace("v","v");
temp = temp.Replace("w","w");
temp = temp.Replace("x","x");
temp = temp.Replace("y","y");
temp = temp.Replace("z","z");
temp = temp.Replace("A","A");
temp = temp.Replace("B","B");
temp = temp.Replace("C","C");
temp = temp.Replace("D","D");
temp = temp.Replace("E","E");
temp = temp.Replace("F","F");
temp = temp.Replace("G","G");
temp = temp.Replace("H","H");
temp = temp.Replace("I","I");
temp = temp.Replace("J","J");
temp = temp.Replace("K","K");
temp = temp.Replace("L","L");
temp = temp.Replace("M","M");
temp = temp.Replace("N","N");
temp = temp.Replace("O","O");
temp = temp.Replace("P","P");
temp = temp.Replace("Q","Q");
temp = temp.Replace("R","R");
temp = temp.Replace("S","S");
temp = temp.Replace("T","T");
temp = temp.Replace("U","U");
temp = temp.Replace("V","V");
temp = temp.Replace("W","W");
temp = temp.Replace("X","X");
temp = temp.Replace("Y","Y");
temp = temp.Replace("Z","Z");
return temp;
}
/**//// <summary>
/// 验证字符串是不是日期格式,因为日期有很多格式,用上面的正则表达式就不如这个方便;
/// </summary>
/// <param name="DatStr">需要判断的字符</param>
/// <returns>结果</returns>
/// <permission cref="System.Security.PermissionSet">private</permission>
private static bool IsDateTime(string DatStr)
{
try
{
Convert.ToDateTime(DatStr) ;
return true ;
}
catch(Exception )
{
return false;
}
}
/**//// <summary>
/// 删除最后一个字符
/// </summary>
/// <param name="str"></param>
/// <returns></returns>
public static string RemoveLastChar(string str)
{
if (str == "")
return "";
else
return str.Substring(0, str.Length - 1);
}
/**//// <summary>
/// 将字符串转换为Color
/// </summary>
/// <param name="color"></param>
/// <returns></returns>
public static Color ToColor(string color)
{
int red, green, blue = 0;
char[] rgb;
color = color.TrimStart('#');
color = Regex.Replace(color.ToLower(), "[g-zG-Z]", "");
switch (color.Length)
{
case 3:
rgb = color.ToCharArray();
red = Convert.ToInt32(rgb[0].ToString() + rgb[0].ToString(), 16);
green = Convert.ToInt32(rgb[1].ToString() + rgb[1].ToString(), 16);
blue = Convert.ToInt32(rgb[2].ToString() + rgb[2].ToString(), 16);
return Color.FromArgb(red, green, blue);
case 6:
rgb = color.ToCharArray();
red = Convert.ToInt32(rgb[0].ToString() + rgb[1].ToString(), 16);
green = Convert.ToInt32(rgb[2].ToString() + rgb[3].ToString(), 16);
blue = Convert.ToInt32(rgb[4].ToString() + rgb[5].ToString(), 16);
return Color.FromArgb(red, green, blue);
default:
return Color.FromName(color);
}
}
/**//// <summary>
/// 将全角数字转换为数字
/// </summary>
/// <param name="SBCCase"></param>
/// <returns></returns>
public static string SBCCaseToNumberic(string SBCCase)
{
char[] c = SBCCase.ToCharArray();
for (int i = 0; i < c.Length; i++)
{
byte[] b = System.Text.Encoding.Unicode.GetBytes(c, i, 1);
if (b.Length == 2)
{
if (b[1] == 255)
{
b[0] = (byte)(b[0] + 32);
b[1] = 0;
c[i] = System.Text.Encoding.Unicode.GetChars(b)[0];
}
}
}
return new string(c);
}
#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(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>
/// 是否是浮点数 可带正负号
/// </summary>
/// <param name="inputData">输入字符串</param>
/// <returns></returns>
public static bool IsEmail(string inputData)
{
Match m = RegEmail.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 消息提示对话框
/**//// <summary>
/// 显示消息提示对话框
/// </summary>
/// <param name="page">当前页面指针,一般为this</param>
/// <param name="msg">提示信息</param>
public static void Show(System.Web.UI.Page page,string msg)
{
Type cstype = page.GetType();
ClientScriptManager clientScript = page.ClientScript;
clientScript.RegisterStartupScript(cstype,"message", "<script language='javascript' defer>alert('" + msg.ToString() + "');</script>");
}
/**//// <summary>
/// 控件点击 消息确认提示框
/// </summary>
/// <param name="page">当前页面指针,一般为this</param>
/// <param name="msg">提示信息</param>
public static void ShowConfirm(System.Web.UI.WebControls.WebControl Control,string msg)
{
//Control.Attributes.Add("onClick","if (!window.confirm('"+msg+"')){return false;}");
Control.Attributes.Add("onclick", "return confirm('" + msg + "');") ;
}
/**//// <summary>
/// 显示消息提示对话框,并进行页面跳转
/// </summary>
/// <param name="page">当前页面指针,一般为this</param>
/// <param name="msg">提示信息</param>
/// <param name="url">跳转的目标URL</param>
public static void ShowAndRedirect(System.Web.UI.Page page,string msg,string url)
{
System.Text.StringBuilder Builder=new System.Text.StringBuilder();
Builder.Append("<script language='javascript' defer>");
Builder.AppendFormat("alert('{0}');",msg);
Builder.AppendFormat("top.location.href='{0}'",url);
Builder.Append("</script>");
Type cstype = page.GetType();
ClientScriptManager clientScript = page.ClientScript;
clientScript.RegisterStartupScript(cstype, "message", Builder.ToString());
}
/**//// <summary>
/// 输出自定义脚本信息
/// </summary>
/// <param name="page">当前页面指针,一般为this</param>
/// <param name="script">输出脚本</param>
public static void ResponseScript(System.Web.UI.Page page,string script)
{
Type cstype = page.GetType();
ClientScriptManager clientScript = page.ClientScript;
clientScript.RegisterStartupScript(cstype, "message", "<script language='javascript' defer>" + script + "</script>");
}
/**//// <summary>
/// 正文分页 - FIXME 最好用dom处理分页
/// </summary>
/// <param name="content">文章内容</param>
/// <param name="currentPageId">当前页码</param>
/// <param name="perPageLength">每页字数</param>
/// <returns></returns>
public static string ContentSplitPage(string content, int pageid, int pageLength)
{
int totalPageCount = 1;
if (content.Length > pageLength)
{
totalPageCount = (int)Math.Ceiling((double)(content.Length / pageLength));
}
if (pageid > totalPageCount)
{
pageid = totalPageCount;
}
StringBuilder sb = new StringBuilder();
string currentContent = string.Empty;
if (pageid == totalPageCount)
{
currentContent = content.Substring(pageLength * (pageid - 1)) + "<br/>";
}
else
{
currentContent = content.Substring(pageLength * (pageid - 1), pageLength) + "<br/>";
}
//开始对内容进行过滤,防治首位<tag>被拆分
if (currentContent.IndexOf("<") > -1)
{
}
return currentContent;
}
/**//// <summary>
/// 新版分页,但是还是有BUG,当第n页和第n+1页都落在一个标签里时,就有问题,但是事实上不可能!! :)
/// </summary>
/// <param name="content"></param>
/// <param name="pageid"></param>
/// <param name="pageLength"></param>
/// <returns></returns>
public static string ContentSplitPageByXml(string content, int pageid, int pageLength)
{
XmlDataDocument doc = new XmlDataDocument();
doc.LoadXml("<msc>" + content + "</msc>");
//大内容分页
int startIndex = (pageid - 1) * pageLength;
int endIndex = pageid * pageLength;
int index = 0;
XmlNodeList list = doc.FirstChild.ChildNodes;
bool isOK = false;
foreach (XmlNode node in list)
{
if (node.NodeType == XmlNodeType.Element)
{
int nodeLength = node.OuterXml.Length;
if (startIndex > index && startIndex < (index + nodeLength))
{
if (isOK == false)
{
startIndex = index + nodeLength;
isOK = true;
}
}
if (endIndex >= index && endIndex < (index + nodeLength))
{
endIndex = index + nodeLength;
if (endIndex > startIndex)
break;
}
index += nodeLength;
}
else if (node.NodeType == XmlNodeType.Text)
{
int nodeLength = node.InnerText.Length;
if (endIndex >= index && endIndex < (index + nodeLength))
{
if (endIndex > startIndex)
break;
}
index += nodeLength;
}
}
string body = doc.OuterXml;
body = body.Substring(5, body.Length - 11);
int bodyLength = body.Length;
if (endIndex > bodyLength)
{
endIndex = bodyLength;
}
body = body.Substring(startIndex, endIndex - startIndex);
return body;
}
/**//// <summary>
/// 数字转换
/// </summary>
/// <param name="num"></param>
/// <returns></returns>
public static string TransferDayOfWeek(int num)
{
string returnString = "";
switch (num)
{
case 1:
returnString = "一";
break;
case 2:
returnString = "二";
break;
case 3:
returnString = "三";
break;
case 4:
returnString = "四";
break;
case 5:
returnString = "五";
break;
case 6:
returnString = "六";
break;
case 0:
returnString = "日";
break;
}
return returnString;
}
#endregion
backup/restore file#region backup/restore file
/**//// <summary>
/// 备份文件
/// </summary>
/// <param name="sourceFileName">源文件名</param>
/// <param name="destFileName">目标文件名</param>
/// <param name="overwrite">当目标文件存在时是否覆盖</param>
/// <returns>操作是否成功</returns>
public static bool BackupFile(string sourceFileName, string destFileName, bool overwrite)
{
if (!System.IO.File.Exists(sourceFileName))
{
throw new FileNotFoundException(sourceFileName + "文件不存在!");
}
if (!overwrite && System.IO.File.Exists(destFileName))
{
return false;
}
try
{
System.IO.File.Copy(sourceFileName, destFileName, true);
return true;
}
catch (Exception e)
{
throw e;
}
}
/**//// <summary>
/// 备份文件,当目标文件存在时覆盖
/// </summary>
/// <param name="sourceFileName">源文件名</param>
/// <param name="destFileName">目标文件名</param>
/// <returns>操作是否成功</returns>
public static bool BackupFile(string sourceFileName, string destFileName)
{
return BackupFile(sourceFileName, destFileName, true);
}
/**//// <summary>
/// 恢复文件
/// </summary>
/// <param name="backupFileName">备份文件名</param>
/// <param name="targetFileName">要恢复的文件名</param>
/// <param name="backupTargetFileName">要恢复文件再次备份的名称,如果为null,则不再备份恢复文件</param>
/// <returns>操作是否成功</returns>
public static bool RestoreFile(string backupFileName, string targetFileName, string backupTargetFileName)
{
try
{
if (!System.IO.File.Exists(backupFileName))
{
throw new FileNotFoundException(backupFileName + "文件不存在!");
}
if (backupTargetFileName != null)
{
if (!System.IO.File.Exists(targetFileName))
{
throw new FileNotFoundException(targetFileName + "文件不存在!无法备份此文件!");
}
else
{
System.IO.File.Copy(targetFileName, backupTargetFileName, true);
}
}
System.IO.File.Delete(targetFileName);
System.IO.File.Copy(backupFileName, targetFileName);
}
catch (Exception e)
{
throw e;
}
return true;
}
public static bool RestoreFile(string backupFileName, string targetFileName)
{
return RestoreFile(backupFileName, targetFileName, null);
}
#endregion
PageBar#region PageBar
/**//// <summary>
/// 读取页面载入时间
/// </summary>
public static string GetPageProcessTime()
{
lock (lockObject)
{
TimeSpan ts = DateTime.Now - Convert.ToDateTime(HttpContext.Current.Items["AppBeginRequestTime"]);
return "<p class='ar fs10'>页面载入时间:<span class='red'>" + ts.TotalSeconds + "</span>秒 </p>";
}
}
#endregion
}
}