/*****************************
* *
* 通用工具类 *
* 时间:2008-05-31 *
* 作者:WJJ *
* *
*****************************/
using System;
using System.Collections.Generic;
using System.Security.Cryptography;
using System.Text;
using System.Text.RegularExpressions;
using System.Runtime.InteropServices;
using System.Web;
using System.Reflection;
using System.Diagnostics;
using System.IO;
using Microsoft.VisualBasic;
using System.Web.UI;
namespace Framework.Common
{
/// <summary>
/// 通用工具
/// 静态类型
/// </summary>
public class Utils
{
public Utils()
{ }
#region << 字符串操作 >>
/// <summary>
/// 自定义的替换字符串函数
/// </summary>
/// <param name="SourceString"></param>
/// <param name="SearchString"></param>
/// <param name="ReplaceString"></param>
/// <param name="IsCaseInsensetive">搜索是否区分大小写</param>
/// <returns></returns>
public static string ReplaceString(string SourceString, string SearchString, string ReplaceString, bool IsCaseInsensetive)
{
return Regex.Replace(SourceString, Regex.Escape(SearchString), ReplaceString, IsCaseInsensetive ? RegexOptions.IgnoreCase : RegexOptions.None);
}
/// <summary>
/// 生成指定数量的html空格符号
/// </summary>
public static string Spaces(int nSpaces)
{
StringBuilder sb = new StringBuilder();
for (int i = 0; i < nSpaces; i++)
{
sb.Append(" ");
}
return sb.ToString();
}
/// <summary>
/// 替换有问题的字符已使其符合SQL语句
/// </summary>
public static string ReplaceStrToSQL(string str)
{
string str2;
if (str == null)
{
str2 = "";
}
else
{
str = str.Replace("'", "''");
str2 = str;
}
return str2;
}
/// <summary>
/// 进行指定的替换(脏字过滤)
/// </summary>
/// <param name="str">需要过滤得字符串</param>
/// <param name="bantext">过滤字符串</param>
/// <returns>过滤后的结果</returns>
public static string StrFilter(string str, string bantext)
{
return ReplaceString(str, bantext, "", true);
}
/// <summary>
/// 清理字符串,结果完全由字母@-符号组成的字符串
/// </summary>
/// <param name="strIn"></param>
/// <returns></returns>
public static string CleanInput(string strIn)
{
return Regex.Replace(strIn.Trim(), @"[^/w/.@-]", "");
}
/// <summary>
/// 分割字符串
/// </summary>
/// <param name="strContent">内容</param>
/// <param name="strSplit">分割符</param>
/// <returns>分割后的字符串数组</returns>
public static string[] SplitString(string strContent, string strSplit)
{
if (strContent.IndexOf(strSplit) < 0)
{
string[] tmp = { strContent };
return tmp;
}
return Regex.Split(strContent, @strSplit.Replace(".", @"/."), RegexOptions.IgnoreCase);
}
/// <summary>
/// 返回字符串的真实长度
/// 汉字2长度 字母1长度
/// </summary>
/// <param name="str">传入的字符串</param>
/// <returns>字符串的真实长度</returns>
public static int GetStringLength(string str)
{
return Encoding.Default.GetBytes(str).Length;
}
/// <summary>
/// 清除Html标签
/// </summary>
/// <param name="content">内容</param>
/// <returns>返回清除后Html标签后的内容</returns>
public static string RemoveHtml(string content)
{
string Reg = @"<[^>]*>";
return Regex.Replace(content, Reg, string.Empty, RegexOptions.IgnoreCase);
}
/// <summary>
/// 为脚本替换特殊字符串
/// " ' "符号;"//"符号;"/"符号
/// </summary>
/// <param name="str"></param>
/// <returns></returns>
public static string ReplaceStrToScript(string str)
{
str = str.Replace("//", "");
str = str.Replace("'", "//'");
str = str.Replace("/"", "///"");
return str;
}
/// <summary>
/// 返回 URL 字符串的编码结果
/// </summary>
/// <param name="str">字符串</param>
/// <returns>编码结果</returns>
public static string UrlEncode(string str)
{
return HttpUtility.UrlEncode(str);
}
/// <summary>
/// 返回 URL 字符串的编码结果
/// </summary>
/// <param name="str">字符串</param>
/// <returns>解码结果</returns>
public static string UrlDecode(string str)
{
return HttpUtility.UrlDecode(str);
}
/// <summary>
/// 删除字符串尾部的回车/换行/空格
/// </summary>
/// <param name="str"></param>
/// <returns></returns>
public static string RTrim(string str)
{
for (int i = str.Length-1; i >= 0; i--)
{
if (str[i].ToString().Equals(" ") || str[i].ToString().Equals("/r") || str[i].ToString().Equals("/n"))
{
str.Remove(i, 1);
}
}
return str;
}
/// <summary>
/// 删除字符串头部的回车/换行/空格
/// </summary>
/// <param name="str"></param>
/// <returns></returns>
public static string LTrim(string str)
{
int len = str.Length - 1;
for (int i = 0; i <= len; i++)
{
if (str.StartsWith(" ")) { str = str.Remove(0, 1); continue; }
else if (str.StartsWith("/r")) { str = str.Remove(0, 1); continue; ;}
else if (str.StartsWith("/n")) { str = str.Remove(0, 1); continue; ;}
else break;
}
return str;
}
#endregion
#region << 数组操作 >>
/// <summary>
/// 判断指定字符串在指定字符串数组中的位置
/// </summary>
/// <param name="strSearch">字符串</param>
/// <param name="stringArray">字符串数组</param>
/// <param name="caseInsensetive">是否不区分大小写, true区分, false区分</param>
/// <returns>字符串在指定字符串数组中的位置, 如不存在则返回-1</returns>
public static int GetInArrayIndex(string strSearch, string[] stringArray, bool IsCaseInsensetive)
{
for (int i = 0; i < stringArray.Length; i++)
{
if (IsCaseInsensetive)
{
if (strSearch.ToLower() == stringArray[i].ToLower())
{
return i;
}
}
else
{
if (strSearch == stringArray[i])
{
return i;
}
}
}
return -1;
}
/// <summary>
/// 判断指定字符串是否属于指定字符串数组中的一个元素
/// </summary>
/// <param name="str">字符串</param>
/// <param name="stringarray">字符串数组</param>
/// <returns>判断结果</returns>
public static bool InArray(string str, string[] stringarray)
{
return GetInArrayIndex(str, stringarray, true) >=0;
}
#endregion
#region << Cookie 操作 >>
/// <summary>
/// 写Cookie操作
/// </summary>
/// <param name="keyName">关键字名称</param>
/// <param name="keyValue">关键字值</param>
public static void WriteCookie(string keyName, string keyValue)
{
Utils.WriteCookie(keyName, keyValue, -1);
}
/// <summary>
/// 写Cookie操作
/// </summary>
/// <param name="keyName">关键字名称</param>
/// <param name="keyValue">关键字值</param>
/// <param name="expires">过时间隔 int</param>
public static void WriteCookie(string keyName, string keyValue, int expires)
{
HttpCookie cookie = HttpContext.Current.Request.Cookies[keyName];
if (cookie == null)
{
cookie = new HttpCookie(keyName);
}
cookie.Value = keyValue;
if (expires != -1)
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 keyName)
{
if (HttpContext.Current.Request.Cookies != null && HttpContext.Current.Request.Cookies[keyName] != null)
{
return HttpContext.Current.Request.Cookies[keyName].Value.ToString();
}
return "";
}
#endregion
#region << IP 地址操作 >>
/// <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?)$");
}
/// <summary>
/// 返回指定IP是否在指定的IP数组所限定的范围内, IP数组内的IP地址可以使用*表示该IP段任意, 例如192.168.1.*
/// </summary>
/// <param name="ip"></param>
/// <param name="iparray"></param>
/// <returns></returns>
public static bool InIPArray(string ip, string[] iparray)
{
string[] userip = Utils.SplitString(ip, @".");
for (int ipIndex = 0; ipIndex < iparray.Length; ipIndex++)
{
string[] tmpip = Utils.SplitString(iparray[ipIndex], @".");
int r = 0;
for (int i = 0; i < tmpip.Length; i++)
{
if (tmpip[i] == "*")
{
return true;
}
if (userip.Length > i)
{
if (tmpip[i] == userip[i])
{
r++;
}
else
{
break;
}
}
else
{
break;
}
}
if (r == 4)
{
return true;
}
}
return false;
}
#endregion
#region << 文件操作(路径/格式) >>
/// <summary>
/// 以指定的ContentType输出指定文件文件
/// </summary>
/// <param name="filepath">文件路径</param>
/// <param name="filename">输出的文件名</param>
/// <param name="filetype">将文件输出时设置的ContentType</param>
public static void ResponseFile(string filepath, string filename, string filetype)
{
Stream iStream = null;
// 缓冲区为10k
byte[] buffer = new Byte[10000];
// 文件长度
int length;
// 需要读的数据长度
long dataToRead;
try
{
// 打开文件
iStream = new FileStream(filepath, FileMode.Open, FileAccess.Read, FileShare.Read);
// 需要读的数据长度
dataToRead = iStream.Length;
HttpContext.Current.Response.ContentType = filetype;
HttpContext.Current.Response.AddHeader("Content-Disposition", "attachment;filename=" + Utils.UrlEncode(filename.Trim()).Replace("+", " "));
while (dataToRead > 0)
{
// 检查客户端是否还处于连接状态
if (HttpContext.Current.Response.IsClientConnected)
{
length = iStream.Read(buffer, 0, 10000);
HttpContext.Current.Response.OutputStream.Write(buffer, 0, length);
HttpContext.Current.Response.Flush();
buffer = new Byte[10000];
dataToRead = dataToRead - length;
}
else
{
// 如果不再连接则跳出死循环
dataToRead = -1;
}
}
}
catch (Exception ex)
{
HttpContext.Current.Response.Write("Error : " + ex.Message);
}
finally
{
if (iStream != null)
{
// 关闭文件
iStream.Close();
}
}
HttpContext.Current.Response.End();
}
/// <summary>
/// 得到网站真实路径
/// </summary>
/// <returns>物理路径</returns>
public static string GetTrueWebstiePath()
{
string WebsitePath = HttpContext.Current.Request.Path;
if (WebsitePath.LastIndexOf("/") != WebsitePath.IndexOf("/"))
{
WebsitePath = WebsitePath.Substring(WebsitePath.IndexOf("/"), WebsitePath.LastIndexOf("/") + 1);
}
else
{
WebsitePath = "/";
}
return WebsitePath;
}
#endregion
#region << 时间日期操作 >>
/// <summary>
/// 时间Time格式判断
/// </summary>
/// <returns></returns>
public static bool IsTime(string timeval)
{
return Regex.IsMatch(timeval, @"^((([0-1]?[0-9])|(2[0-3])):([0-5]?[0-9])(:[0-5]?[0-9])?)$");
}
#endregion
#region << 检测操作 >>
/// <summary>
/// 判断给定的字符串数组(strNumber)中的数据是不是都为数值型
/// </summary>
/// <param name="strNumber">要确认的字符串数组</param>
/// <returns>是则返加true 不是则返回 false</returns>
public static bool IsNumberArray(string[] strNumber)
{
if (strNumber == null)
{
return false;
}
if (strNumber.Length < 1)
{
return false;
}
foreach (string id in strNumber)
{
if (!IsNumber(id))
{
return false;
}
}
return true;
}
/// <summary>
/// 判断给定的字符串(strNumber)是否是数值型,如"123" / "123.98" 返回为 True
/// </summary>
/// <param name="strNumber">要确认的字符串</param>
/// <returns>是则返加true 不是则返回 false</returns>
public static bool IsNumber(string strNumber)
{
return new Regex(@"^([0-9])[0-9]*(/./w*)?$").IsMatch(strNumber);
}
#endregion
}
}