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.IO;
using System.Text.RegularExpressions;
using System.Diagnostics;
using System.Security.Cryptography;
using System.Text;
namespace Common
{
/// <summary>
/// ClsCommon 的摘要说明
/// </summary>
public class ClsCommon
{
/// <summary>
///网站名称
/// </summary>
public static string WebSiteName;
/// <summary>
/// 检查用户是否登陆
/// </summary>
/// <param name="strUserId">用户ID</param>
public static bool ChkLogin(object strUserId)
{
if (strUserId == null)
{
System.Web.UI.Page aPage = (System.Web.UI.Page)System.Web.HttpContext.Current.Handler;
string url = aPage.ResolveUrl("../Login.aspx");
AlerRedirect1("你不是合法用户或登录超时,请重新登录!", url);
return false;
}
return true;
}
#region 提示对话框方面的函数
///<summary>
///提示脚本,并直接返回到某一特定页(不在iframe内)
///</summary>
///<param name="strMessage"></param>
///<param name="strNavigateTo"></param>
///<remarks></remarks>
public static void AlerRedirect(string strMessage, string strNavigateTo)
{
System.Web.HttpContext.Current.Response.Write("<script type='text/javascript' language='JavaScript'>");
System.Web.HttpContext.Current.Response.Write("alert('" + strMessage + "');parent.location = '" + strNavigateTo + "'");
System.Web.HttpContext.Current.Response.Write("</script>");
}
public static void AlerRedirect1(string strMessage, string strNavigateTo)
{
System.Web.UI.Page aPage = (System.Web.UI.Page)System.Web.HttpContext.Current.Handler;
aPage.ClientScript.RegisterClientScriptBlock(aPage.GetType(), "", "<script type='text/javascript' language='JavaScript'>msgShow('提示','" + strMessage + "','warning');parent.location = '" + strNavigateTo + "'</script>");
}
/// <summary>
/// 显示提示(仅提示)
/// </summary>
/// <param name="strMessage"></param>
/// <remarks></remarks>
public static void Alert(string strMessage)
{
System.Web.UI.Page aPage = (System.Web.UI.Page)System.Web.HttpContext.Current.Handler;
aPage.ClientScript.RegisterClientScriptBlock(aPage.GetType(), "", "<script type='text/javascript' language='JavaScript'>alert('" + strMessage + "');</script>");
}
/ <summary>
/ 提示,AJAX,无JQUERY
/ </summary>
/ <param name="strMsg"></param>
//public static void AlerInAjax(string strMsg)
//{
// System.Web.UI.Page aPage = (System.Web.UI.Page)System.Web.HttpContext.Current.Handler;
// ScriptManager.RegisterStartupScript(aPage, aPage.GetType(), "", "alert('" + strMsg + "');", true);
//}
#region AJAX中用到的提示脚本
#endregion
#endregion
#region 下载文件
public static bool DownloadFile(string saveFileName, string filename, HttpResponse Response)
{
try
{
Response.Clear();
Response.Charset = "utf-8";
Response.Buffer = true;
//this.EnableViewState = false;
Response.ContentEncoding = System.Text.Encoding.UTF8;
Response.AppendHeader("Content-Disposition", "attachment;filename=" + HttpUtility.UrlEncode(saveFileName, Encoding.UTF8));
Response.WriteFile(filename);
Response.Flush();
Response.Close();
Response.End();
}
catch (Exception)
{
return false;
}
return true;
}
#endregion
#region 加密和解密功能
///<summary>
/// 加密
/// </summary>
/// <param name="str"></param>
/// <param name="key"></param>
/// <returns></returns>
public static string Encode(string str, string key)
{
if (string.IsNullOrEmpty(str)) return "";
DESCryptoServiceProvider provider = new DESCryptoServiceProvider();
provider.Key = Encoding.ASCII.GetBytes(key.Substring(0, 8));
provider.IV = Encoding.ASCII.GetBytes(key.Substring(0, 8));
byte[] bytes = Encoding.GetEncoding("GB2312").GetBytes(str);
MemoryStream stream = new MemoryStream();
CryptoStream stream2 = new CryptoStream(stream, provider.CreateEncryptor(), CryptoStreamMode.Write);
stream2.Write(bytes, 0, bytes.Length);
stream2.FlushFinalBlock();
StringBuilder builder = new StringBuilder();
foreach (byte num in stream.ToArray())
{
builder.AppendFormat("{0:X2}", num);
}
stream.Close();
return builder.ToString();
}
/// <summary>
/// Des 解密 GB2312
/// </summary>
/// <param name="str">Desc string</param>
/// <param name="key">Key ,必须为8位 </param>
/// <returns></returns>
public static string Decode(string str, string key)
{
try
{
DESCryptoServiceProvider provider = new DESCryptoServiceProvider();
provider.Key = Encoding.ASCII.GetBytes(key.Substring(0, 8));
provider.IV = Encoding.ASCII.GetBytes(key.Substring(0, 8));
byte[] buffer = new byte[str.Length / 2];
for (int i = 0; i < (str.Length / 2); i++)
{
int num2 = Convert.ToInt32(str.Substring(i * 2, 2), 0x10);
buffer[i] = (byte)num2;
}
MemoryStream stream = new MemoryStream();
CryptoStream stream2 = new CryptoStream(stream, provider.CreateDecryptor(), CryptoStreamMode.Write);
stream2.Write(buffer, 0, buffer.Length);
stream2.FlushFinalBlock();
stream.Close();
return Encoding.GetEncoding("GB2312").GetString(stream.ToArray());
}
catch (Exception)
{
return "";
}
}
#endregion
/// <summary>
/// 说明:SubStr用来将字符串保留到指定长度,将超出部分用“...”代替。
/// 返回值:处理后的这符串。
/// 参数: sString原字符串。
/// nLeng长度。
/// 创建日期:2009-1-1
/// 创建人:吕明华
/// </summary>
public static string SubStr(string sString, int nLeng)
{
string sNewStr;
if (sString.Length <= nLeng)
{
sNewStr = sString;
}
else
{
sNewStr = sString.Substring(0, nLeng);
}
return sNewStr;
}
/// <summary>
/// 把时间生成为编号
/// </summary>
/// <returns></returns>
public static string getIdByDate()
{
return DateTime.Now.ToString("yyyyMMddhhssmm");
}
#region 符号过滤
/// <summary>
/// 去掉","
/// </summary>
/// <param name="str">参数</param>
/// <param name="iLength">取字符串长度</param>
/// <param name="Type">0重左则开始取1重右则开始取</param>
/// <returns></returns>
public static string TrimStr(string str, int iLength, string Type)
{
if (str != "")
{
if (Type == "0")
{
if (str.Substring(0, 1) == ",")
{
str = str.Substring(1);
}
}
else
{
if (str.Length >= iLength)
{
str = str.Substring(str.Length - iLength, 1);
}
}
}
return str;
}
/// <summary>
/// 对于SQL中使用的字符串,加"'"
/// </summary>
/// <param name="str"></param>
/// <returns></returns>
public static string AddStr(string str)
{
if (str != "")
{
//TrimStr(str);
string temp = str.Replace(",", "','");
temp = "'" + temp + "'";
str = temp;
}
else
{
str = "''";
}
return str;
}
**************************
** 判断是否是数字组合 **
**************************
public bool IsNumber(string strDate)
{
if (strDate == null)
{
return false;
}
if (strDate.Equals(string.Empty))
{
return false;
}
Regex numRegex = new Regex(@"0*[0-9][0-9]*$");
return numRegex.IsMatch(strDate);
}
******************
** 过滤JS代码 **
******************
public string moveJS(string strString)
{
string str;
str = strString;
if (str != null)
{
str = str.Replace("\\", "\\\\");
str = str.Replace(((char)34).ToString(), "\\\"");
str = str.Replace(((char)39).ToString(), "\\'");
str = str.Replace(((char)13).ToString(), "\\n");
str = str.Replace(((char)10).ToString(), "\\r");
str = str.Replace("'", "'");
str = str.Replace(" ", " ");
str = str.Replace(((char)9).ToString(), " ");
str = str.Replace("<", "<");
str = str.Replace(">", ">");
}
return str;
}
********************
** 过滤HTML代码 **
********************
public string moveHtml(string strString)
{
string str;
str = strString;
if (str != null)
{
str = str.Replace(" ", " ");
str = str.Replace("<", "<");
str = str.Replace(">", ">");
str = str.Replace("|", "");
str = str.Replace(((char)9).ToString(), " ");
str = str.Replace(((char)34).ToString(), """);
str = str.Replace(((char)39).ToString(), "'");
str = str.Replace(((char)13).ToString() + ((char)10).ToString(), "<br>");
}
return str;
}
******************
** 过滤'"符号 **
******************
public string MoveBidStr(string strString)
{
string str;
str = strString;
if (str != null)
{
str = str.Replace("'", "''");
str = str.Replace(((char)39).ToString(), ((char)39 + (char)39).ToString());
}
return str;
}
#endregion
#region 隐藏和显示
public static void trvVis(System.Web.UI.WebControls.Button btn, System.Web.UI.HtmlControls.HtmlTableRow atrv)
{
if (atrv.Visible == true)
{
btn.Text = "显示";
atrv.Visible = false;
}
else
{
btn.Text = "隐藏";
atrv.Visible = true;
}
}
#endregion
#region 分页
///<summary>
///<param name="DLName">DataList控件</param>
/// <param name="ds">DataSet数据集</param>
/// <param name="labBackPage">显示分页总数</param>
/// <param name="labPage">显示当前页数</param>
/// <param name="lnkbtnBack">跳转到最后一页</param>
/// <param name="lnkbtnNext">跳转到下一页</param>
/// <param name="lnkbtnOne">跳转到第一页</param>
/// <param name="lnkbtnUp">跳转到上一页</param>
///</summary>
//labPage 显示当前页数
//labBackPage 显示分页总数
//lnkbtnOne 跳转到第一页
//lnkbtnUp 跳转到上一页
//lnkbtnNext 跳转到下一页
//lnkbtnBack 跳转到最后一页
//将数据绑定到DataList控件上,再使用PagedDataSource类实现DataList控件的分页功能
public static void SetPage(Label labCount, Label labPage, Label labBackPage, LinkButton lnkbtnOne, LinkButton lnkbtnUp, LinkButton lnkbtnNext, LinkButton lnkbtnBack, DataSet ds, DataList DLName, int pageSize)
{
//取得当前页的页码
int curpage = Convert.ToInt32(labPage.Text);
//使用PagedDataSource类实现DataList控件的分页功能
PagedDataSource ps = new PagedDataSource();
//获取数据集
// DataSet ds = CC.GetDataSet("SQL语句");
//ps.DataSource = ds.Tables[0].DefaultView;
ps.DataSource = ds.Tables[0].DefaultView;
//是否可以分页
ps.AllowPaging = true;
//显示数量
ps.PageSize = pageSize;
//取得当前页的页码
ps.CurrentPageIndex = curpage - 1;
lnkbtnUp.Enabled = true;
lnkbtnNext.Enabled = true;
lnkbtnBack.Enabled = true;
lnkbtnOne.Enabled = true;
if (curpage == 1)
{
//不显示第一页按钮
lnkbtnOne.Enabled = false;
//不显示上一页按钮
lnkbtnUp.Enabled = false;
}
if (curpage == ps.PageCount)
{
//不显示下一页
lnkbtnNext.Enabled = false;
//不显示最后一页
lnkbtnBack.Enabled = false;
}
//显示分页数量
labBackPage.Text = Convert.ToString(ps.PageCount);
//数据总量
labCount.Text = Convert.ToString(ds.Tables[0].Rows.Count);
//绑定DataList控件
DLName.DataSource = ps;
DLName.DataBind();
}
///<summary>
///<param name="DLName">Repeater控件</param>
/// <param name="ds">DataSet数据集</param>
/// <param name="labBackPage">显示分页总数</param>
/// <param name="labPage">显示当前页数</param>
/// <param name="lnkbtnBack">跳转到最后一页</param>
/// <param name="lnkbtnNext">跳转到下一页</param>
/// <param name="lnkbtnOne">跳转到第一页</param>
/// <param name="lnkbtnUp">跳转到上一页</param>
///</summary>
//labPage 显示当前页数
//labBackPage 显示分页总数
//lnkbtnOne 跳转到第一页
//lnkbtnUp 跳转到上一页
//lnkbtnNext 跳转到下一页
//lnkbtnBack 跳转到最后一页
//将数据绑定到Repeater控件上,再使用PagedDataSource类实现Repeater控件的分页功能
public static void SetPage(Label labCount, Label labPage, Label labBackPage, LinkButton lnkbtnOne, LinkButton lnkbtnUp, LinkButton lnkbtnNext, LinkButton lnkbtnBack, DataTable ds, Repeater DLName, int pageSize)
{
//取得当前页的页码
int curpage = Convert.ToInt32(labPage.Text);
//使用PagedDataSource类实现DataList控件的分页功能
PagedDataSource ps = new PagedDataSource();
//获取数据集
// DataSet ds = CC.GetDataSet("SQL语句");
//ps.DataSource = ds.Tables[0].DefaultView;
ps.DataSource = ds.DefaultView;
//是否可以分页
ps.AllowPaging = true;
//显示数量
ps.PageSize = pageSize;
//取得当前页的页码
ps.CurrentPageIndex = curpage - 1;
lnkbtnUp.Enabled = true;
lnkbtnNext.Enabled = true;
lnkbtnBack.Enabled = true;
lnkbtnOne.Enabled = true;
if (curpage == 1)
{
//不显示第一页按钮
lnkbtnOne.Enabled = false;
//不显示上一页按钮
lnkbtnUp.Enabled = false;
}
if (curpage == ps.PageCount)
{
//不显示下一页
lnkbtnNext.Enabled = false;
//不显示最后一页
lnkbtnBack.Enabled = false;
}
//显示分页数量
labBackPage.Text = Convert.ToString(ps.PageCount);
//数据总量
labCount.Text = Convert.ToString(ds.Rows.Count);
//绑定DataList控件
DLName.DataSource = ps;
DLName.DataBind();
}
#endregion
/// <summary>
/// FileUpLoad控件上传文件处理
/// </summary>
/// <param name="file">FileUpLoad.PostedFile</param>
/// <param name="isNameByDate">文件名是否按时间命名,例如:文件名20101212123456789</param>
/// <param name="isRandom">文件名是否在末尾生成三位随机数</param>
/// <param name="SavePath">保存位置</param>
/// <returns>文件名(包含后缀名)</returns>
public static string SaveUpFile(HttpPostedFile file, bool isNameByDate, bool isRandom, string SavePath)
{
try
{
//不存在就创建
if (!Directory.Exists(SavePath))
{
Directory.CreateDirectory(SavePath);
}
string filename = Path.GetFileNameWithoutExtension(file.FileName); //文件名(不包含扩展名)
string fileExtension = Path.GetExtension(file.FileName).ToLower(); //文件扩展名
//if (isNameByDate) filename += DateTime.Now.ToString().Replace("-", "").Replace(" ", "").Replace(":", "");
绝对路径+文件名+后缀名
//string FullFileName = "";
//Random rdm = new Random();
循环30次检测文件是否存在
//for (int i = 0; i < 30; i++)
//{
// filename = isRandom ? filename + rdm.Next(999999).ToString() : filename;
// //filename = rdm.Next(999).ToString();
// FullFileName = SavePath + filename + fileExtension;
// if (!File.Exists(FullFileName))
// {
// //保存文件
// file.SaveAs(FullFileName);
// //返回文件名+后缀名
// return filename + fileExtension;
// }
//}
//Alert("上传文件发生错误,请重试!");
//return "Error";
DateTime dateNow = DateTime.Now;
string nameDateNow = "";
//绝对路径+文件名+后缀名
string FullFileName = "";
int whileNum = 0;
Random rdm = new Random();
//循环检测文件是否存在
do
{
nameDateNow = dateNow.Year.ToString() + //年
dateNow.Month.ToString() + //月
dateNow.Day.ToString() + //日
dateNow.Hour.ToString() + //时
dateNow.Minute.ToString() + //分
dateNow.Second.ToString() + //秒
dateNow.Millisecond.ToString() + //毫秒
rdm.Next(999).ToString(); //3位随机数
FullFileName = SavePath + nameDateNow + fileExtension;
whileNum++;
} while (System.IO.File.Exists(FullFileName) && whileNum < 30);
if (whileNum == 30)
{
ClsCommon.Alert("上传图片发生错误,请重新保存!");
return "Error";
}
//保存文件
file.SaveAs(FullFileName);
//返回文件名+后缀名
return nameDateNow + fileExtension;
}
catch (Exception)
{
return "Error";
}
}
/// <summary>
/// 获得字符串长度,全角和汉字占2位
/// </summary>
/// <param name="str"></param>
/// <returns></returns>
public static int GetStrLength(string str)
{
int strLength = 0;
int asc;
for (int i = 0; i < str.Length; i++)
{
asc = Convert.ToChar(str.Substring(i, 1));
strLength = asc < 0 || asc > 127 ? strLength += 2 : strLength++;
}
return strLength;
}
/// <summary>
/// 不良文字过滤
/// </summary>
/// <param name="msg"></param>
/// <returns></returns>
public static string FilterBadWords(string msg)
{
System.Web.UI.Page aPage = (System.Web.UI.Page)System.Web.HttpContext.Current.Handler;
String strFilePath = aPage.Server.MapPath("~/a.log");//此处为ASP.NET写法获取站点根路径文件
System.IO.StreamReader sr = new System.IO.StreamReader(strFilePath, System.Text.Encoding.GetEncoding("gbk"));//此处应填写你屏蔽的关键文件(相当于词库)的编码。一般是GBK 和 UTF-8
String[] textlist = sr.ReadToEnd().Split('|');
sr.Close();
foreach (String t in textlist)
{
msg = msg.Replace(t, "");//不良文字替换成空或者其他操作//或者设置一个标志直接返回不替换,告诉用户这个标志的文字是不良文字
}
return msg;
}
/// <summary>
/// 清除HTML函数
/// </summary>
/// <param name="Htmlstring"></param>
/// <returns></returns>
public static string NoHTML(string Htmlstring)
{
//删除脚本
Htmlstring = Regex.Replace(Htmlstring, @"<script[^>]*?>.*?</script>", "", RegexOptions.IgnoreCase);
//删除HTML
Htmlstring = Regex.Replace(Htmlstring, @"<(.[^>]*)>", "", RegexOptions.IgnoreCase);
Htmlstring = Regex.Replace(Htmlstring, @"([\r\n])[\s]+", "", RegexOptions.IgnoreCase);
Htmlstring = Regex.Replace(Htmlstring, @"-->", "", RegexOptions.IgnoreCase);
Htmlstring = Regex.Replace(Htmlstring, @"<!--.*", "", RegexOptions.IgnoreCase);
//<script></script>
Htmlstring = Regex.Replace(Htmlstring, @"&(quot|#34);", "\"", RegexOptions.IgnoreCase);
Htmlstring = Regex.Replace(Htmlstring, @"&(amp|#38);", "&", RegexOptions.IgnoreCase);
Htmlstring = Regex.Replace(Htmlstring, @"&(lt|#60);", "<", RegexOptions.IgnoreCase);
Htmlstring = Regex.Replace(Htmlstring, @"&(gt|#62);", ">", RegexOptions.IgnoreCase);
Htmlstring = Regex.Replace(Htmlstring, @"&(nbsp|#160);", " ", RegexOptions.IgnoreCase);
Htmlstring = Regex.Replace(Htmlstring, @"&(iexcl|#161);", "\xa1", RegexOptions.IgnoreCase);
Htmlstring = Regex.Replace(Htmlstring, @"&(cent|#162);", "\xa2", RegexOptions.IgnoreCase);
Htmlstring = Regex.Replace(Htmlstring, @"&(pound|#163);", "\xa3", RegexOptions.IgnoreCase);
Htmlstring = Regex.Replace(Htmlstring, @"&(copy|#169);", "\xa9", RegexOptions.IgnoreCase);
Htmlstring = Regex.Replace(Htmlstring, @"&#(\d+);", "", RegexOptions.IgnoreCase);
Htmlstring.Replace("<", "");
Htmlstring.Replace(">", "");
Htmlstring.Replace("\r\n", "");
Htmlstring = HttpContext.Current.Server.HtmlEncode(Htmlstring).Trim();
return Htmlstring;
}
/// <summary>
/// 写入js脚本
/// </summary>
/// <param name="jsCode">js脚本</param>
public static void WriteJavaScript(string jsCode)
{
System.Web.UI.Page aPage = (System.Web.UI.Page)System.Web.HttpContext.Current.Handler;
aPage.ClientScript.RegisterClientScriptBlock(aPage.GetType(), "", "<script language='JavaScript'>" + jsCode + "</script>");
}
/// <summary>
/// 获取HTML中的所有<img>元素的src属性,此方法返回捕获到的说路径组成的数组
/// </summary>
/// <param name="sHtmlText">HTML代码</param>
/// <returns></returns>
public static string[] GetHtmlImageUrlList(string sHtmlText)
{
// 定义正则表达式用来匹配 img 标签
Regex regImg = new Regex(@"<img\b[^<>]*?\bsrc[\s\t\r\n]*=[\s\t\r\n]*[""']?[\s\t\r\n]*(?<imgUrl>[^\s\t\r\n""'<>]*)[^<>]*?/?[\s\t\r\n]*>", RegexOptions.IgnoreCase);
// 搜索匹配的字符串
MatchCollection matches = regImg.Matches(sHtmlText);
int i = 0;
string[] sUrlList = new string[matches.Count];
// 取得匹配项列表
foreach (Match match in matches)
{
sUrlList[i++] = match.Groups["imgUrl"].Value;
}
return sUrlList;
}
#region 快速导航
public static string GetscrollBanner()
{
System.Web.UI.Page Page = (System.Web.UI.Page)System.Web.HttpContext.Current.Handler;
return "<script type=\"text/javascript\" src=\"" + Page.ResolveUrl("~/js/scrollBanner.js") + "\"></script>" +
"<div id=\"rwc\" style=\"width: 74px; height: auto; border: #CCCCCC 0px solid; padding: 5px;\">" +
" <table width=\"74\" border=\"0\" cellpadding=\"0\" cellspacing=\"0\">" +
" <tr>" +
" <td height=\"29\" background=\"" + Page.ResolveUrl("~/images/fd_4.gif") + "\" class=\"kjdh\">" +
" 快捷导航<a href='javascript:toSmall();' id='spa1'><span id='sp1' class='kjdh'> ▲</span></a></td>" +
" </tr>" +
" <tr>" +
" <td height=\"4\">" +
" </td>" +
" </tr>" +
" <tr>" +
" <td>" +
" <table width=\"74\" border=\"0\" cellpadding=\"0\" cellspacing=\"0\" id=\"fun\">" +
" <tr>" +
" <td height=\"38\" background='" + Page.ResolveUrl("~/images/fd_5.gif") + "' class=\"kjdhstyle\">" +
" <a href='" + Page.ResolveUrl("~/Person/Default.aspx") + "' target=\"_blank\">我要求职 </a>" +
" </td>" +
" </tr>" +
" <tr>" +
" <td height=\"38\" background=\"" + Page.ResolveUrl("~/images/fd_6.gif") + "\" class=\"kjdhstyle\">" +
" <a href=\"" + Page.ResolveUrl("~/Company/Default.aspx") + "\" target=\"_blank\">我要招聘 </a>" +
" </td>" +
" </tr>" +
" <tr>" +
" <td height=\"38\" background=\"" + Page.ResolveUrl("~/images/fd_6.gif") + "\" class=\"kjdhstyle\">" +
" <a href=\"" + Page.ResolveUrl("~/Record.aspx") + "\" target=\"_blank\">到档查询 </a>" +
" </td>" +
" </tr>" +
" <tr>" +
" <td height=\"38\" background=\"" + Page.ResolveUrl("~/images/fd_6.gif") + "\" class=\"kjdhstyle\">" +
" <a href=\"" + Page.ResolveUrl("~/OrgService.aspx?id=3") + "\" target=\"_blank\">文件下载 </a>" +
" </td>" +
" </tr>" +
" <tr>" +
" <td height=\"38\" background=\"" + Page.ResolveUrl("~/images/fd_6.gif") + "\" class=\"kjdhstyle\">" +
" <a href=\"" + Page.ResolveUrl("~/Msg.aspx?id=2") + "\" target=\"_blank\">业务问答 </a>" +
" </td>" +
" </tr>" +
" <tr>" +
" <td height=\"38\" background=\"" + Page.ResolveUrl("~/images/fd_7.gif") + "\" class=\"kjdhstyle\">" +
" <a href=\"" + Page.ResolveUrl("~/SiteMap.aspx") + "\" target=\"_blank\">网站地图 </a>" +
" </td>" +
" </tr>" +
" </table>" +
" </td>" +
" </tr>" +
" <tr>" +
" <tr>" +
" <td height=\"4\">" +
" </td>" +
" </tr>" +
" <td>" +
" <a target=\"_blank\" href=\" http://wpa.qq.com/msgrd?v=3&uin=2209962026&site=qq&menu=yes\">" +
" <img border=\"0\" width=\"74\" src=\" http://wpa.qq.com/pa?p=2:2209962026:42\" alt=\"点击这里给我发消息\"" +
" title=\"点击这里给我发消息\"></a>" +
" </td>" +
" </tr>" +
" </table>" +
"</div>" +
"<script language=\"javascript\" type=\"text/javascript\"> " +
" var state='1';" +
" var o = document.getElementById('fun');" +
" var sp1= document.getElementById('sp1');" +
" var spa1 = document.getElementById('spa1');" +
" function toSmall()" +
" {" +
" if (state=='1')" +
" {" +
" o.style.display = 'none'; " +
" state='0';" +
" sp1.innerHTML='▼';" +
" spa1.title='展开快捷导航'; " +
" }" +
" else" +
" {" +
" o.style.display = 'block'; " +
" state='1';" +
" sp1.innerHTML='▲';" +
" spa1.title='收起快捷导航';" +
" }" +
" } " +
"</script>";
}
#endregion
/// <summary>
/// 过滤输入
/// </summary>
/// <param name="Str"></param>
/// <returns></returns>
public static string SafeSql(string Str)
{
Str = NoHTML(Str);
Str = FilterBadWords(Str);
if (Str.Trim() == "") return "";
string pattern = @"select|insert|delete|from|count\(|drop table|update|truncate|asc\(|mid\(|char\(|xp_cmdshell|exec master|netlocalgroup administrators|:|net user|""|or|and";
Str = Regex.Replace(Str, pattern, "", RegexOptions.IgnoreCase);
return Str;
}
public static string FiltrateSql(string Str)
{
if (Str.Trim() == "") return "";
Str = Str.Replace("'", "''");
//过滤脚本
Str = Regex.Replace(Str, @"&(lt|#60);", "<", RegexOptions.IgnoreCase);
Str = Regex.Replace(Str, @"&(gt|#62);", ">", RegexOptions.IgnoreCase);
Str = Regex.Replace(Str, @"<script[^>]*?>.*?</script>", "", RegexOptions.IgnoreCase);
//过滤SQL
string pattern = @"select|insert|delete|from|count\(|drop table|update|truncate|asc\(|mid\(|char\(|xp_cmdshell|exec master|netlocalgroup administrators|:|net user|""|or|and";
Str = Regex.Replace(Str, pattern, "", RegexOptions.IgnoreCase);
return Str;
}
///<summary>
///提示脚本,并直接返回到某一特定页(在iframe内)
///</summary>
///<param name="strMessage"></param>
///<param name="strNavigateTo"></param>
///<remarks></remarks>
public static void AlerRedirectX(string strMessage, string strNavigateTo)
{
System.Web.HttpContext.Current.Response.Write("<script language='JavaScript'>");
System.Web.HttpContext.Current.Response.Write("alert('" + strMessage + "');location.href = '" + strNavigateTo + "'");
System.Web.HttpContext.Current.Response.Write("</script>");
}
#region 身份证验证
/// <summary>
/// 验证身份证号码
/// </summary>
/// <param name="Id"></param>
/// <returns></returns>
public static bool CheckIDCard(string Id)
{
if (Id.Length == 18)
{
bool check = CheckIDCard18(Id);
return check;
}
else if (Id.Length == 15)
{
bool check = CheckIDCard15(Id);
return check;
}
else
{
return false;
}
}
private static bool CheckIDCard18(string Id)
{
long n = 0;
if (long.TryParse(Id.Remove(17), out n) == false || n < Math.Pow(10, 16) || long.TryParse(Id.Replace('x', '0').Replace('X', '0'), out n) == false)
{
return false;//数字验证
}
string address = "11x22x35x44x53x12x23x36x45x54x13x31x37x46x61x14x32x41x50x62x15x33x42x51x63x21x34x43x52x64x65x71x81x82x91";
if (address.IndexOf(Id.Remove(2)) == -1)
{
return false;//省份验证
}
string birth = Id.Substring(6, 8).Insert(6, "-").Insert(4, "-");
DateTime time = new DateTime();
if (DateTime.TryParse(birth, out time) == false)
{
return false;//生日验证
}
string[] arrVarifyCode = ("1,0,x,9,8,7,6,5,4,3,2").Split(',');
string[] Wi = ("7,9,10,5,8,4,2,1,6,3,7,9,10,5,8,4,2").Split(',');
char[] Ai = Id.Remove(17).ToCharArray();
int sum = 0;
for (int i = 0; i < 17; i++)
{
sum += int.Parse(Wi[i]) * int.Parse(Ai[i].ToString());
}
int y = -1;
Math.DivRem(sum, 11, out y);
if (arrVarifyCode[y] != Id.Substring(17, 1).ToLower())
{
return false;//校验码验证
}
return true;//符合GB11643-1999标准
}
private static bool CheckIDCard15(string Id)
{
long n = 0;
if (long.TryParse(Id, out n) == false || n < Math.Pow(10, 14))
{
return false;//数字验证
}
string address = "11x22x35x44x53x12x23x36x45x54x13x31x37x46x61x14x32x41x50x62x15x33x42x51x63x21x34x43x52x64x65x71x81x82x91";
if (address.IndexOf(Id.Remove(2)) == -1)
{
return false;//省份验证
}
string birth = Id.Substring(6, 6).Insert(4, "-").Insert(2, "-");
DateTime time = new DateTime();
if (DateTime.TryParse(birth, out time) == false)
{
return false;//生日验证
}
return true;//符合15位身份证标准
}
/// <summary>
/// 根据身份证号获取生日
/// </summary>
/// <param name="IdCard"></param>
/// <returns></returns>
public static string GetBrithdayFromIdCard(string IdCard)
{
string rtn = "1900-01-01";
if (IdCard.Length == 15)
{
rtn = IdCard.Substring(6, 6).Insert(4, "-").Insert(2, "-");
}
else if (IdCard.Length == 18)
{
rtn = IdCard.Substring(6, 8).Insert(6, "-").Insert(4, "-");
}
return rtn;
}
/// <summary>
/// 根据身份证获取性别
/// </summary>
/// <param name="IdCard"></param>
/// <returns></returns>
public static string GetSexFromIdCard(string IdCard)
{
string rtn;
string tmp = "";
if (IdCard.Length == 15)
{
tmp = IdCard.Substring(IdCard.Length - 3);
}
else if (IdCard.Length == 18)
{
tmp = IdCard.Substring(IdCard.Length - 4);
tmp = tmp.Substring(0, 3);
}
int sx = int.Parse(tmp);
int outNum;
Math.DivRem(sx, 2, out outNum);
if (outNum == 0)
{
rtn = "女";
}
else
{
rtn = "男";
}
return rtn;
}
#endregion
/// <summary>
/// 执行外部程序
/// </summary>
/// <param name="cmd"></param>
/// <param name="args"></param>
public static void ExcutedCmd(string cmd, string args)
{
using (Process p = new Process())
{
ProcessStartInfo psi = new ProcessStartInfo(cmd, args);
p.StartInfo = psi;
p.Start();
p.WaitForExit();
}
}
/*========================================以下代码模块 为小笨熊项目填写 ========================================*/
/// <summary>
/// Repeater绑定方法 小闫填写
/// </summary>
/// <param name="RePeaterId"></param>
/// <param name="dt"></param>
public static void GetRepeaterDataBind(System.Web.UI.WebControls.Repeater RePeaterId, DataTable dt)
{
if (dt != null)
{
RePeaterId.DataSource = dt;
RePeaterId.DataBind();
}
}
/// <summary>
/// 把一列的值合并成一个字符串
/// </summary>
/// <param name="dt"></param>
/// <returns></returns>
public static string ReVal(DataTable dt)
{
string ReValue = "";
if (dt.Rows.Count > 0)
{
for (int i = 0; i < dt.Rows.Count; i++)
{
ReValue+= dt.Rows[i]["CodeValue"].ToString()+",";
}
}
return ReValue;
}
#region 加密、解密、随机数
/// <summary>
/// 参数加密,默认密钥 "XiaoBenXiong_"
/// </summary>
public static string RE_Encode(string str)
{
return Encode(str.Trim(), "EChuShu1");
}
/// <summary>
/// 参数解密,密钥默认 "XiaoBenXiong_"
/// </summary>
public static string RE_Decode(string str)
{
return Decode(str.Trim(), "EChuShu1");
}
/// <summary>
/// 参数加密,key自定义 8为长度
/// </summary>
public static string RE_Encode(string str, string key)
{
return Encode(str.Trim(), key);
}
/// <summary>
/// 参数解密,key自定义 8为长度
/// </summary>
public static string RE_Decode(string str, string key)
{
return Decode(str.Trim(), key);
}
/// <summary>
/// 返回随机数 使用当前年月日做种
/// </summary>
/// <returns></returns>
public static string RE_Random()
{
Random rd = new Random(Convert.ToInt32(DateTime.Now.ToString("yyyyMMdd"))); //无参即为使用系统时钟为种子
return rd.Next().ToString();
}
#endregion
}
}
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.IO;
using System.Text.RegularExpressions;
using System.Diagnostics;
using System.Security.Cryptography;
using System.Text;
namespace Common
{
/// <summary>
/// ClsCommon 的摘要说明
/// </summary>
public class ClsCommon
{
/// <summary>
///网站名称
/// </summary>
public static string WebSiteName;
/// <summary>
/// 检查用户是否登陆
/// </summary>
/// <param name="strUserId">用户ID</param>
public static bool ChkLogin(object strUserId)
{
if (strUserId == null)
{
System.Web.UI.Page aPage = (System.Web.UI.Page)System.Web.HttpContext.Current.Handler;
string url = aPage.ResolveUrl("../Login.aspx");
AlerRedirect1("你不是合法用户或登录超时,请重新登录!", url);
return false;
}
return true;
}
#region 提示对话框方面的函数
///<summary>
///提示脚本,并直接返回到某一特定页(不在iframe内)
///</summary>
///<param name="strMessage"></param>
///<param name="strNavigateTo"></param>
///<remarks></remarks>
public static void AlerRedirect(string strMessage, string strNavigateTo)
{
System.Web.HttpContext.Current.Response.Write("<script type='text/javascript' language='JavaScript'>");
System.Web.HttpContext.Current.Response.Write("alert('" + strMessage + "');parent.location = '" + strNavigateTo + "'");
System.Web.HttpContext.Current.Response.Write("</script>");
}
public static void AlerRedirect1(string strMessage, string strNavigateTo)
{
System.Web.UI.Page aPage = (System.Web.UI.Page)System.Web.HttpContext.Current.Handler;
aPage.ClientScript.RegisterClientScriptBlock(aPage.GetType(), "", "<script type='text/javascript' language='JavaScript'>msgShow('提示','" + strMessage + "','warning');parent.location = '" + strNavigateTo + "'</script>");
}
/// <summary>
/// 显示提示(仅提示)
/// </summary>
/// <param name="strMessage"></param>
/// <remarks></remarks>
public static void Alert(string strMessage)
{
System.Web.UI.Page aPage = (System.Web.UI.Page)System.Web.HttpContext.Current.Handler;
aPage.ClientScript.RegisterClientScriptBlock(aPage.GetType(), "", "<script type='text/javascript' language='JavaScript'>alert('" + strMessage + "');</script>");
}
/ <summary>
/ 提示,AJAX,无JQUERY
/ </summary>
/ <param name="strMsg"></param>
//public static void AlerInAjax(string strMsg)
//{
// System.Web.UI.Page aPage = (System.Web.UI.Page)System.Web.HttpContext.Current.Handler;
// ScriptManager.RegisterStartupScript(aPage, aPage.GetType(), "", "alert('" + strMsg + "');", true);
//}
#region AJAX中用到的提示脚本
#endregion
#endregion
#region 下载文件
public static bool DownloadFile(string saveFileName, string filename, HttpResponse Response)
{
try
{
Response.Clear();
Response.Charset = "utf-8";
Response.Buffer = true;
//this.EnableViewState = false;
Response.ContentEncoding = System.Text.Encoding.UTF8;
Response.AppendHeader("Content-Disposition", "attachment;filename=" + HttpUtility.UrlEncode(saveFileName, Encoding.UTF8));
Response.WriteFile(filename);
Response.Flush();
Response.Close();
Response.End();
}
catch (Exception)
{
return false;
}
return true;
}
#endregion
#region 加密和解密功能
///<summary>
/// 加密
/// </summary>
/// <param name="str"></param>
/// <param name="key"></param>
/// <returns></returns>
public static string Encode(string str, string key)
{
if (string.IsNullOrEmpty(str)) return "";
DESCryptoServiceProvider provider = new DESCryptoServiceProvider();
provider.Key = Encoding.ASCII.GetBytes(key.Substring(0, 8));
provider.IV = Encoding.ASCII.GetBytes(key.Substring(0, 8));
byte[] bytes = Encoding.GetEncoding("GB2312").GetBytes(str);
MemoryStream stream = new MemoryStream();
CryptoStream stream2 = new CryptoStream(stream, provider.CreateEncryptor(), CryptoStreamMode.Write);
stream2.Write(bytes, 0, bytes.Length);
stream2.FlushFinalBlock();
StringBuilder builder = new StringBuilder();
foreach (byte num in stream.ToArray())
{
builder.AppendFormat("{0:X2}", num);
}
stream.Close();
return builder.ToString();
}
/// <summary>
/// Des 解密 GB2312
/// </summary>
/// <param name="str">Desc string</param>
/// <param name="key">Key ,必须为8位 </param>
/// <returns></returns>
public static string Decode(string str, string key)
{
try
{
DESCryptoServiceProvider provider = new DESCryptoServiceProvider();
provider.Key = Encoding.ASCII.GetBytes(key.Substring(0, 8));
provider.IV = Encoding.ASCII.GetBytes(key.Substring(0, 8));
byte[] buffer = new byte[str.Length / 2];
for (int i = 0; i < (str.Length / 2); i++)
{
int num2 = Convert.ToInt32(str.Substring(i * 2, 2), 0x10);
buffer[i] = (byte)num2;
}
MemoryStream stream = new MemoryStream();
CryptoStream stream2 = new CryptoStream(stream, provider.CreateDecryptor(), CryptoStreamMode.Write);
stream2.Write(buffer, 0, buffer.Length);
stream2.FlushFinalBlock();
stream.Close();
return Encoding.GetEncoding("GB2312").GetString(stream.ToArray());
}
catch (Exception)
{
return "";
}
}
#endregion
/// <summary>
/// 说明:SubStr用来将字符串保留到指定长度,将超出部分用“...”代替。
/// 返回值:处理后的这符串。
/// 参数: sString原字符串。
/// nLeng长度。
/// 创建日期:2009-1-1
/// 创建人:吕明华
/// </summary>
public static string SubStr(string sString, int nLeng)
{
string sNewStr;
if (sString.Length <= nLeng)
{
sNewStr = sString;
}
else
{
sNewStr = sString.Substring(0, nLeng);
}
return sNewStr;
}
/// <summary>
/// 把时间生成为编号
/// </summary>
/// <returns></returns>
public static string getIdByDate()
{
return DateTime.Now.ToString("yyyyMMddhhssmm");
}
#region 符号过滤
/// <summary>
/// 去掉","
/// </summary>
/// <param name="str">参数</param>
/// <param name="iLength">取字符串长度</param>
/// <param name="Type">0重左则开始取1重右则开始取</param>
/// <returns></returns>
public static string TrimStr(string str, int iLength, string Type)
{
if (str != "")
{
if (Type == "0")
{
if (str.Substring(0, 1) == ",")
{
str = str.Substring(1);
}
}
else
{
if (str.Length >= iLength)
{
str = str.Substring(str.Length - iLength, 1);
}
}
}
return str;
}
/// <summary>
/// 对于SQL中使用的字符串,加"'"
/// </summary>
/// <param name="str"></param>
/// <returns></returns>
public static string AddStr(string str)
{
if (str != "")
{
//TrimStr(str);
string temp = str.Replace(",", "','");
temp = "'" + temp + "'";
str = temp;
}
else
{
str = "''";
}
return str;
}
**************************
** 判断是否是数字组合 **
**************************
public bool IsNumber(string strDate)
{
if (strDate == null)
{
return false;
}
if (strDate.Equals(string.Empty))
{
return false;
}
Regex numRegex = new Regex(@"0*[0-9][0-9]*$");
return numRegex.IsMatch(strDate);
}
******************
** 过滤JS代码 **
******************
public string moveJS(string strString)
{
string str;
str = strString;
if (str != null)
{
str = str.Replace("\\", "\\\\");
str = str.Replace(((char)34).ToString(), "\\\"");
str = str.Replace(((char)39).ToString(), "\\'");
str = str.Replace(((char)13).ToString(), "\\n");
str = str.Replace(((char)10).ToString(), "\\r");
str = str.Replace("'", "'");
str = str.Replace(" ", " ");
str = str.Replace(((char)9).ToString(), " ");
str = str.Replace("<", "<");
str = str.Replace(">", ">");
}
return str;
}
********************
** 过滤HTML代码 **
********************
public string moveHtml(string strString)
{
string str;
str = strString;
if (str != null)
{
str = str.Replace(" ", " ");
str = str.Replace("<", "<");
str = str.Replace(">", ">");
str = str.Replace("|", "");
str = str.Replace(((char)9).ToString(), " ");
str = str.Replace(((char)34).ToString(), """);
str = str.Replace(((char)39).ToString(), "'");
str = str.Replace(((char)13).ToString() + ((char)10).ToString(), "<br>");
}
return str;
}
******************
** 过滤'"符号 **
******************
public string MoveBidStr(string strString)
{
string str;
str = strString;
if (str != null)
{
str = str.Replace("'", "''");
str = str.Replace(((char)39).ToString(), ((char)39 + (char)39).ToString());
}
return str;
}
#endregion
#region 隐藏和显示
public static void trvVis(System.Web.UI.WebControls.Button btn, System.Web.UI.HtmlControls.HtmlTableRow atrv)
{
if (atrv.Visible == true)
{
btn.Text = "显示";
atrv.Visible = false;
}
else
{
btn.Text = "隐藏";
atrv.Visible = true;
}
}
#endregion
#region 分页
///<summary>
///<param name="DLName">DataList控件</param>
/// <param name="ds">DataSet数据集</param>
/// <param name="labBackPage">显示分页总数</param>
/// <param name="labPage">显示当前页数</param>
/// <param name="lnkbtnBack">跳转到最后一页</param>
/// <param name="lnkbtnNext">跳转到下一页</param>
/// <param name="lnkbtnOne">跳转到第一页</param>
/// <param name="lnkbtnUp">跳转到上一页</param>
///</summary>
//labPage 显示当前页数
//labBackPage 显示分页总数
//lnkbtnOne 跳转到第一页
//lnkbtnUp 跳转到上一页
//lnkbtnNext 跳转到下一页
//lnkbtnBack 跳转到最后一页
//将数据绑定到DataList控件上,再使用PagedDataSource类实现DataList控件的分页功能
public static void SetPage(Label labCount, Label labPage, Label labBackPage, LinkButton lnkbtnOne, LinkButton lnkbtnUp, LinkButton lnkbtnNext, LinkButton lnkbtnBack, DataSet ds, DataList DLName, int pageSize)
{
//取得当前页的页码
int curpage = Convert.ToInt32(labPage.Text);
//使用PagedDataSource类实现DataList控件的分页功能
PagedDataSource ps = new PagedDataSource();
//获取数据集
// DataSet ds = CC.GetDataSet("SQL语句");
//ps.DataSource = ds.Tables[0].DefaultView;
ps.DataSource = ds.Tables[0].DefaultView;
//是否可以分页
ps.AllowPaging = true;
//显示数量
ps.PageSize = pageSize;
//取得当前页的页码
ps.CurrentPageIndex = curpage - 1;
lnkbtnUp.Enabled = true;
lnkbtnNext.Enabled = true;
lnkbtnBack.Enabled = true;
lnkbtnOne.Enabled = true;
if (curpage == 1)
{
//不显示第一页按钮
lnkbtnOne.Enabled = false;
//不显示上一页按钮
lnkbtnUp.Enabled = false;
}
if (curpage == ps.PageCount)
{
//不显示下一页
lnkbtnNext.Enabled = false;
//不显示最后一页
lnkbtnBack.Enabled = false;
}
//显示分页数量
labBackPage.Text = Convert.ToString(ps.PageCount);
//数据总量
labCount.Text = Convert.ToString(ds.Tables[0].Rows.Count);
//绑定DataList控件
DLName.DataSource = ps;
DLName.DataBind();
}
///<summary>
///<param name="DLName">Repeater控件</param>
/// <param name="ds">DataSet数据集</param>
/// <param name="labBackPage">显示分页总数</param>
/// <param name="labPage">显示当前页数</param>
/// <param name="lnkbtnBack">跳转到最后一页</param>
/// <param name="lnkbtnNext">跳转到下一页</param>
/// <param name="lnkbtnOne">跳转到第一页</param>
/// <param name="lnkbtnUp">跳转到上一页</param>
///</summary>
//labPage 显示当前页数
//labBackPage 显示分页总数
//lnkbtnOne 跳转到第一页
//lnkbtnUp 跳转到上一页
//lnkbtnNext 跳转到下一页
//lnkbtnBack 跳转到最后一页
//将数据绑定到Repeater控件上,再使用PagedDataSource类实现Repeater控件的分页功能
public static void SetPage(Label labCount, Label labPage, Label labBackPage, LinkButton lnkbtnOne, LinkButton lnkbtnUp, LinkButton lnkbtnNext, LinkButton lnkbtnBack, DataTable ds, Repeater DLName, int pageSize)
{
//取得当前页的页码
int curpage = Convert.ToInt32(labPage.Text);
//使用PagedDataSource类实现DataList控件的分页功能
PagedDataSource ps = new PagedDataSource();
//获取数据集
// DataSet ds = CC.GetDataSet("SQL语句");
//ps.DataSource = ds.Tables[0].DefaultView;
ps.DataSource = ds.DefaultView;
//是否可以分页
ps.AllowPaging = true;
//显示数量
ps.PageSize = pageSize;
//取得当前页的页码
ps.CurrentPageIndex = curpage - 1;
lnkbtnUp.Enabled = true;
lnkbtnNext.Enabled = true;
lnkbtnBack.Enabled = true;
lnkbtnOne.Enabled = true;
if (curpage == 1)
{
//不显示第一页按钮
lnkbtnOne.Enabled = false;
//不显示上一页按钮
lnkbtnUp.Enabled = false;
}
if (curpage == ps.PageCount)
{
//不显示下一页
lnkbtnNext.Enabled = false;
//不显示最后一页
lnkbtnBack.Enabled = false;
}
//显示分页数量
labBackPage.Text = Convert.ToString(ps.PageCount);
//数据总量
labCount.Text = Convert.ToString(ds.Rows.Count);
//绑定DataList控件
DLName.DataSource = ps;
DLName.DataBind();
}
#endregion
/// <summary>
/// FileUpLoad控件上传文件处理
/// </summary>
/// <param name="file">FileUpLoad.PostedFile</param>
/// <param name="isNameByDate">文件名是否按时间命名,例如:文件名20101212123456789</param>
/// <param name="isRandom">文件名是否在末尾生成三位随机数</param>
/// <param name="SavePath">保存位置</param>
/// <returns>文件名(包含后缀名)</returns>
public static string SaveUpFile(HttpPostedFile file, bool isNameByDate, bool isRandom, string SavePath)
{
try
{
//不存在就创建
if (!Directory.Exists(SavePath))
{
Directory.CreateDirectory(SavePath);
}
string filename = Path.GetFileNameWithoutExtension(file.FileName); //文件名(不包含扩展名)
string fileExtension = Path.GetExtension(file.FileName).ToLower(); //文件扩展名
//if (isNameByDate) filename += DateTime.Now.ToString().Replace("-", "").Replace(" ", "").Replace(":", "");
绝对路径+文件名+后缀名
//string FullFileName = "";
//Random rdm = new Random();
循环30次检测文件是否存在
//for (int i = 0; i < 30; i++)
//{
// filename = isRandom ? filename + rdm.Next(999999).ToString() : filename;
// //filename = rdm.Next(999).ToString();
// FullFileName = SavePath + filename + fileExtension;
// if (!File.Exists(FullFileName))
// {
// //保存文件
// file.SaveAs(FullFileName);
// //返回文件名+后缀名
// return filename + fileExtension;
// }
//}
//Alert("上传文件发生错误,请重试!");
//return "Error";
DateTime dateNow = DateTime.Now;
string nameDateNow = "";
//绝对路径+文件名+后缀名
string FullFileName = "";
int whileNum = 0;
Random rdm = new Random();
//循环检测文件是否存在
do
{
nameDateNow = dateNow.Year.ToString() + //年
dateNow.Month.ToString() + //月
dateNow.Day.ToString() + //日
dateNow.Hour.ToString() + //时
dateNow.Minute.ToString() + //分
dateNow.Second.ToString() + //秒
dateNow.Millisecond.ToString() + //毫秒
rdm.Next(999).ToString(); //3位随机数
FullFileName = SavePath + nameDateNow + fileExtension;
whileNum++;
} while (System.IO.File.Exists(FullFileName) && whileNum < 30);
if (whileNum == 30)
{
ClsCommon.Alert("上传图片发生错误,请重新保存!");
return "Error";
}
//保存文件
file.SaveAs(FullFileName);
//返回文件名+后缀名
return nameDateNow + fileExtension;
}
catch (Exception)
{
return "Error";
}
}
/// <summary>
/// 获得字符串长度,全角和汉字占2位
/// </summary>
/// <param name="str"></param>
/// <returns></returns>
public static int GetStrLength(string str)
{
int strLength = 0;
int asc;
for (int i = 0; i < str.Length; i++)
{
asc = Convert.ToChar(str.Substring(i, 1));
strLength = asc < 0 || asc > 127 ? strLength += 2 : strLength++;
}
return strLength;
}
/// <summary>
/// 不良文字过滤
/// </summary>
/// <param name="msg"></param>
/// <returns></returns>
public static string FilterBadWords(string msg)
{
System.Web.UI.Page aPage = (System.Web.UI.Page)System.Web.HttpContext.Current.Handler;
String strFilePath = aPage.Server.MapPath("~/a.log");//此处为ASP.NET写法获取站点根路径文件
System.IO.StreamReader sr = new System.IO.StreamReader(strFilePath, System.Text.Encoding.GetEncoding("gbk"));//此处应填写你屏蔽的关键文件(相当于词库)的编码。一般是GBK 和 UTF-8
String[] textlist = sr.ReadToEnd().Split('|');
sr.Close();
foreach (String t in textlist)
{
msg = msg.Replace(t, "");//不良文字替换成空或者其他操作//或者设置一个标志直接返回不替换,告诉用户这个标志的文字是不良文字
}
return msg;
}
/// <summary>
/// 清除HTML函数
/// </summary>
/// <param name="Htmlstring"></param>
/// <returns></returns>
public static string NoHTML(string Htmlstring)
{
//删除脚本
Htmlstring = Regex.Replace(Htmlstring, @"<script[^>]*?>.*?</script>", "", RegexOptions.IgnoreCase);
//删除HTML
Htmlstring = Regex.Replace(Htmlstring, @"<(.[^>]*)>", "", RegexOptions.IgnoreCase);
Htmlstring = Regex.Replace(Htmlstring, @"([\r\n])[\s]+", "", RegexOptions.IgnoreCase);
Htmlstring = Regex.Replace(Htmlstring, @"-->", "", RegexOptions.IgnoreCase);
Htmlstring = Regex.Replace(Htmlstring, @"<!--.*", "", RegexOptions.IgnoreCase);
//<script></script>
Htmlstring = Regex.Replace(Htmlstring, @"&(quot|#34);", "\"", RegexOptions.IgnoreCase);
Htmlstring = Regex.Replace(Htmlstring, @"&(amp|#38);", "&", RegexOptions.IgnoreCase);
Htmlstring = Regex.Replace(Htmlstring, @"&(lt|#60);", "<", RegexOptions.IgnoreCase);
Htmlstring = Regex.Replace(Htmlstring, @"&(gt|#62);", ">", RegexOptions.IgnoreCase);
Htmlstring = Regex.Replace(Htmlstring, @"&(nbsp|#160);", " ", RegexOptions.IgnoreCase);
Htmlstring = Regex.Replace(Htmlstring, @"&(iexcl|#161);", "\xa1", RegexOptions.IgnoreCase);
Htmlstring = Regex.Replace(Htmlstring, @"&(cent|#162);", "\xa2", RegexOptions.IgnoreCase);
Htmlstring = Regex.Replace(Htmlstring, @"&(pound|#163);", "\xa3", RegexOptions.IgnoreCase);
Htmlstring = Regex.Replace(Htmlstring, @"&(copy|#169);", "\xa9", RegexOptions.IgnoreCase);
Htmlstring = Regex.Replace(Htmlstring, @"&#(\d+);", "", RegexOptions.IgnoreCase);
Htmlstring.Replace("<", "");
Htmlstring.Replace(">", "");
Htmlstring.Replace("\r\n", "");
Htmlstring = HttpContext.Current.Server.HtmlEncode(Htmlstring).Trim();
return Htmlstring;
}
/// <summary>
/// 写入js脚本
/// </summary>
/// <param name="jsCode">js脚本</param>
public static void WriteJavaScript(string jsCode)
{
System.Web.UI.Page aPage = (System.Web.UI.Page)System.Web.HttpContext.Current.Handler;
aPage.ClientScript.RegisterClientScriptBlock(aPage.GetType(), "", "<script language='JavaScript'>" + jsCode + "</script>");
}
/// <summary>
/// 获取HTML中的所有<img>元素的src属性,此方法返回捕获到的说路径组成的数组
/// </summary>
/// <param name="sHtmlText">HTML代码</param>
/// <returns></returns>
public static string[] GetHtmlImageUrlList(string sHtmlText)
{
// 定义正则表达式用来匹配 img 标签
Regex regImg = new Regex(@"<img\b[^<>]*?\bsrc[\s\t\r\n]*=[\s\t\r\n]*[""']?[\s\t\r\n]*(?<imgUrl>[^\s\t\r\n""'<>]*)[^<>]*?/?[\s\t\r\n]*>", RegexOptions.IgnoreCase);
// 搜索匹配的字符串
MatchCollection matches = regImg.Matches(sHtmlText);
int i = 0;
string[] sUrlList = new string[matches.Count];
// 取得匹配项列表
foreach (Match match in matches)
{
sUrlList[i++] = match.Groups["imgUrl"].Value;
}
return sUrlList;
}
#region 快速导航
public static string GetscrollBanner()
{
System.Web.UI.Page Page = (System.Web.UI.Page)System.Web.HttpContext.Current.Handler;
return "<script type=\"text/javascript\" src=\"" + Page.ResolveUrl("~/js/scrollBanner.js") + "\"></script>" +
"<div id=\"rwc\" style=\"width: 74px; height: auto; border: #CCCCCC 0px solid; padding: 5px;\">" +
" <table width=\"74\" border=\"0\" cellpadding=\"0\" cellspacing=\"0\">" +
" <tr>" +
" <td height=\"29\" background=\"" + Page.ResolveUrl("~/images/fd_4.gif") + "\" class=\"kjdh\">" +
" 快捷导航<a href='javascript:toSmall();' id='spa1'><span id='sp1' class='kjdh'> ▲</span></a></td>" +
" </tr>" +
" <tr>" +
" <td height=\"4\">" +
" </td>" +
" </tr>" +
" <tr>" +
" <td>" +
" <table width=\"74\" border=\"0\" cellpadding=\"0\" cellspacing=\"0\" id=\"fun\">" +
" <tr>" +
" <td height=\"38\" background='" + Page.ResolveUrl("~/images/fd_5.gif") + "' class=\"kjdhstyle\">" +
" <a href='" + Page.ResolveUrl("~/Person/Default.aspx") + "' target=\"_blank\">我要求职 </a>" +
" </td>" +
" </tr>" +
" <tr>" +
" <td height=\"38\" background=\"" + Page.ResolveUrl("~/images/fd_6.gif") + "\" class=\"kjdhstyle\">" +
" <a href=\"" + Page.ResolveUrl("~/Company/Default.aspx") + "\" target=\"_blank\">我要招聘 </a>" +
" </td>" +
" </tr>" +
" <tr>" +
" <td height=\"38\" background=\"" + Page.ResolveUrl("~/images/fd_6.gif") + "\" class=\"kjdhstyle\">" +
" <a href=\"" + Page.ResolveUrl("~/Record.aspx") + "\" target=\"_blank\">到档查询 </a>" +
" </td>" +
" </tr>" +
" <tr>" +
" <td height=\"38\" background=\"" + Page.ResolveUrl("~/images/fd_6.gif") + "\" class=\"kjdhstyle\">" +
" <a href=\"" + Page.ResolveUrl("~/OrgService.aspx?id=3") + "\" target=\"_blank\">文件下载 </a>" +
" </td>" +
" </tr>" +
" <tr>" +
" <td height=\"38\" background=\"" + Page.ResolveUrl("~/images/fd_6.gif") + "\" class=\"kjdhstyle\">" +
" <a href=\"" + Page.ResolveUrl("~/Msg.aspx?id=2") + "\" target=\"_blank\">业务问答 </a>" +
" </td>" +
" </tr>" +
" <tr>" +
" <td height=\"38\" background=\"" + Page.ResolveUrl("~/images/fd_7.gif") + "\" class=\"kjdhstyle\">" +
" <a href=\"" + Page.ResolveUrl("~/SiteMap.aspx") + "\" target=\"_blank\">网站地图 </a>" +
" </td>" +
" </tr>" +
" </table>" +
" </td>" +
" </tr>" +
" <tr>" +
" <tr>" +
" <td height=\"4\">" +
" </td>" +
" </tr>" +
" <td>" +
" <a target=\"_blank\" href=\" http://wpa.qq.com/msgrd?v=3&uin=2209962026&site=qq&menu=yes\">" +
" <img border=\"0\" width=\"74\" src=\" http://wpa.qq.com/pa?p=2:2209962026:42\" alt=\"点击这里给我发消息\"" +
" title=\"点击这里给我发消息\"></a>" +
" </td>" +
" </tr>" +
" </table>" +
"</div>" +
"<script language=\"javascript\" type=\"text/javascript\"> " +
" var state='1';" +
" var o = document.getElementById('fun');" +
" var sp1= document.getElementById('sp1');" +
" var spa1 = document.getElementById('spa1');" +
" function toSmall()" +
" {" +
" if (state=='1')" +
" {" +
" o.style.display = 'none'; " +
" state='0';" +
" sp1.innerHTML='▼';" +
" spa1.title='展开快捷导航'; " +
" }" +
" else" +
" {" +
" o.style.display = 'block'; " +
" state='1';" +
" sp1.innerHTML='▲';" +
" spa1.title='收起快捷导航';" +
" }" +
" } " +
"</script>";
}
#endregion
/// <summary>
/// 过滤输入
/// </summary>
/// <param name="Str"></param>
/// <returns></returns>
public static string SafeSql(string Str)
{
Str = NoHTML(Str);
Str = FilterBadWords(Str);
if (Str.Trim() == "") return "";
string pattern = @"select|insert|delete|from|count\(|drop table|update|truncate|asc\(|mid\(|char\(|xp_cmdshell|exec master|netlocalgroup administrators|:|net user|""|or|and";
Str = Regex.Replace(Str, pattern, "", RegexOptions.IgnoreCase);
return Str;
}
public static string FiltrateSql(string Str)
{
if (Str.Trim() == "") return "";
Str = Str.Replace("'", "''");
//过滤脚本
Str = Regex.Replace(Str, @"&(lt|#60);", "<", RegexOptions.IgnoreCase);
Str = Regex.Replace(Str, @"&(gt|#62);", ">", RegexOptions.IgnoreCase);
Str = Regex.Replace(Str, @"<script[^>]*?>.*?</script>", "", RegexOptions.IgnoreCase);
//过滤SQL
string pattern = @"select|insert|delete|from|count\(|drop table|update|truncate|asc\(|mid\(|char\(|xp_cmdshell|exec master|netlocalgroup administrators|:|net user|""|or|and";
Str = Regex.Replace(Str, pattern, "", RegexOptions.IgnoreCase);
return Str;
}
///<summary>
///提示脚本,并直接返回到某一特定页(在iframe内)
///</summary>
///<param name="strMessage"></param>
///<param name="strNavigateTo"></param>
///<remarks></remarks>
public static void AlerRedirectX(string strMessage, string strNavigateTo)
{
System.Web.HttpContext.Current.Response.Write("<script language='JavaScript'>");
System.Web.HttpContext.Current.Response.Write("alert('" + strMessage + "');location.href = '" + strNavigateTo + "'");
System.Web.HttpContext.Current.Response.Write("</script>");
}
#region 身份证验证
/// <summary>
/// 验证身份证号码
/// </summary>
/// <param name="Id"></param>
/// <returns></returns>
public static bool CheckIDCard(string Id)
{
if (Id.Length == 18)
{
bool check = CheckIDCard18(Id);
return check;
}
else if (Id.Length == 15)
{
bool check = CheckIDCard15(Id);
return check;
}
else
{
return false;
}
}
private static bool CheckIDCard18(string Id)
{
long n = 0;
if (long.TryParse(Id.Remove(17), out n) == false || n < Math.Pow(10, 16) || long.TryParse(Id.Replace('x', '0').Replace('X', '0'), out n) == false)
{
return false;//数字验证
}
string address = "11x22x35x44x53x12x23x36x45x54x13x31x37x46x61x14x32x41x50x62x15x33x42x51x63x21x34x43x52x64x65x71x81x82x91";
if (address.IndexOf(Id.Remove(2)) == -1)
{
return false;//省份验证
}
string birth = Id.Substring(6, 8).Insert(6, "-").Insert(4, "-");
DateTime time = new DateTime();
if (DateTime.TryParse(birth, out time) == false)
{
return false;//生日验证
}
string[] arrVarifyCode = ("1,0,x,9,8,7,6,5,4,3,2").Split(',');
string[] Wi = ("7,9,10,5,8,4,2,1,6,3,7,9,10,5,8,4,2").Split(',');
char[] Ai = Id.Remove(17).ToCharArray();
int sum = 0;
for (int i = 0; i < 17; i++)
{
sum += int.Parse(Wi[i]) * int.Parse(Ai[i].ToString());
}
int y = -1;
Math.DivRem(sum, 11, out y);
if (arrVarifyCode[y] != Id.Substring(17, 1).ToLower())
{
return false;//校验码验证
}
return true;//符合GB11643-1999标准
}
private static bool CheckIDCard15(string Id)
{
long n = 0;
if (long.TryParse(Id, out n) == false || n < Math.Pow(10, 14))
{
return false;//数字验证
}
string address = "11x22x35x44x53x12x23x36x45x54x13x31x37x46x61x14x32x41x50x62x15x33x42x51x63x21x34x43x52x64x65x71x81x82x91";
if (address.IndexOf(Id.Remove(2)) == -1)
{
return false;//省份验证
}
string birth = Id.Substring(6, 6).Insert(4, "-").Insert(2, "-");
DateTime time = new DateTime();
if (DateTime.TryParse(birth, out time) == false)
{
return false;//生日验证
}
return true;//符合15位身份证标准
}
/// <summary>
/// 根据身份证号获取生日
/// </summary>
/// <param name="IdCard"></param>
/// <returns></returns>
public static string GetBrithdayFromIdCard(string IdCard)
{
string rtn = "1900-01-01";
if (IdCard.Length == 15)
{
rtn = IdCard.Substring(6, 6).Insert(4, "-").Insert(2, "-");
}
else if (IdCard.Length == 18)
{
rtn = IdCard.Substring(6, 8).Insert(6, "-").Insert(4, "-");
}
return rtn;
}
/// <summary>
/// 根据身份证获取性别
/// </summary>
/// <param name="IdCard"></param>
/// <returns></returns>
public static string GetSexFromIdCard(string IdCard)
{
string rtn;
string tmp = "";
if (IdCard.Length == 15)
{
tmp = IdCard.Substring(IdCard.Length - 3);
}
else if (IdCard.Length == 18)
{
tmp = IdCard.Substring(IdCard.Length - 4);
tmp = tmp.Substring(0, 3);
}
int sx = int.Parse(tmp);
int outNum;
Math.DivRem(sx, 2, out outNum);
if (outNum == 0)
{
rtn = "女";
}
else
{
rtn = "男";
}
return rtn;
}
#endregion
/// <summary>
/// 执行外部程序
/// </summary>
/// <param name="cmd"></param>
/// <param name="args"></param>
public static void ExcutedCmd(string cmd, string args)
{
using (Process p = new Process())
{
ProcessStartInfo psi = new ProcessStartInfo(cmd, args);
p.StartInfo = psi;
p.Start();
p.WaitForExit();
}
}
/*========================================以下代码模块 为小笨熊项目填写 ========================================*/
/// <summary>
/// Repeater绑定方法 小闫填写
/// </summary>
/// <param name="RePeaterId"></param>
/// <param name="dt"></param>
public static void GetRepeaterDataBind(System.Web.UI.WebControls.Repeater RePeaterId, DataTable dt)
{
if (dt != null)
{
RePeaterId.DataSource = dt;
RePeaterId.DataBind();
}
}
/// <summary>
/// 把一列的值合并成一个字符串
/// </summary>
/// <param name="dt"></param>
/// <returns></returns>
public static string ReVal(DataTable dt)
{
string ReValue = "";
if (dt.Rows.Count > 0)
{
for (int i = 0; i < dt.Rows.Count; i++)
{
ReValue+= dt.Rows[i]["CodeValue"].ToString()+",";
}
}
return ReValue;
}
#region 加密、解密、随机数
/// <summary>
/// 参数加密,默认密钥 "XiaoBenXiong_"
/// </summary>
public static string RE_Encode(string str)
{
return Encode(str.Trim(), "EChuShu1");
}
/// <summary>
/// 参数解密,密钥默认 "XiaoBenXiong_"
/// </summary>
public static string RE_Decode(string str)
{
return Decode(str.Trim(), "EChuShu1");
}
/// <summary>
/// 参数加密,key自定义 8为长度
/// </summary>
public static string RE_Encode(string str, string key)
{
return Encode(str.Trim(), key);
}
/// <summary>
/// 参数解密,key自定义 8为长度
/// </summary>
public static string RE_Decode(string str, string key)
{
return Decode(str.Trim(), key);
}
/// <summary>
/// 返回随机数 使用当前年月日做种
/// </summary>
/// <returns></returns>
public static string RE_Random()
{
Random rd = new Random(Convert.ToInt32(DateTime.Now.ToString("yyyyMMdd"))); //无参即为使用系统时钟为种子
return rd.Next().ToString();
}
#endregion
}
}