using System;
using System.Collections.Generic;
using System.Text;
using System.Data;
using System.Data.SqlClient;
using System.Xml;
using System.Xml.Schema;
using System.Xml.Serialization;
using System.Xml.XPath;
using System.Xml.Xsl;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Collections;
using System.Text.RegularExpressions;
using System.Diagnostics;
using System.IO;
using System.Drawing;
using System.Runtime.InteropServices;
using System.Security.Cryptography;
using Microsoft.VisualBasic;
using System.Net;
using System.Reflection;
namespace DAL
{
public class DBHelper
{
public const string ASSEMBLY_VERSION = "3.0.0";
private static Regex RegexBr = new Regex(@"(/r/n)", RegexOptions.IgnoreCase);
public static Regex RegexFont = new Regex(@"" + "/".*?/"" + @">([/s/S]+?)", GetRegexCompiledOptions());
private static FileVersionInfo AssemblyFileVersion = FileVersionInfo.GetVersionInfo(Assembly.GetExecutingAssembly().Location);
private static string TemplateCookieName = string.Format("dnttemplateid_{0}_{1}_{2}", AssemblyFileVersion.FileMajorPart, AssemblyFileVersion.FileMinorPart, AssemblyFileVersion.FileBuildPart);
///
/// 通过SubString截取字符串
///
/// 传入将要格式化的字符串
/// 要截取字符串的实际长度
///
sNewStr
public static string SubString(string strs, int sLength)
{
if (strs.Length <= sLength)
{
return strs;
}
int nStrLength = sLength - 1;
string sNewStr = strs.Substring(0, sLength);
//sNewStr = sNewStr + "Mores...";
return sNewStr;
}
///
/// 得到正则编译参数设置
///
///
参数设置
public static RegexOptions GetRegexCompiledOptions()
{
return RegexOptions.None;
}
///
/// 返回字符串真实长度, 1个汉字长度为
///
///
字符长度
public static int GetStringLength(string str)
{
return Encoding.Default.GetBytes(str).Length;
}
public static bool IsCompriseStr(string str, string stringarray, string strsplit)
{
if (StrIsNullOrEmpty(stringarray))
return false;
str = str.ToLower();
string[] stringArray = SplitString(stringarray.ToLower(), strsplit);
for (int i = 0; i < stringArray.Length; i++)
{
if (str.IndexOf(stringArray[i]) > -1)
{
return true;
}
}
return false;
}
///
/// 判断指定字符串在指定字符串数组中的位置
///
/// 字符串
/// 字符串数组
/// 是否不区分大小写, true为不区分, false为区分
///
字符串在指定字符串数组中的位置, 如不存在则返回-1
public static int GetInArrayID(string strSearch, string[] stringArray, bool caseInsensetive)
{
for (int i = 0; i < stringArray.Length; i++)
{
if (caseInsensetive)
{
if (strSearch.ToLower() == stringArray[i].ToLower())
return i;
}
else if (strSearch == stringArray[i])
return i;
}
return -1;
}
///
/// 判断指定字符串在指定字符串数组中的位置
///
/// 字符串
/// 字符串数组
///
字符串在指定字符串数组中的位置, 如不存在则返回-1
public static int GetInArrayID(string strSearch, string[] stringArray)
{
return GetInArrayID(strSearch, stringArray, true);
}
///
/// 判断指定字符串是否属于指定字符串数组中的一个元素
///
/// 字符串
/// 字符串数组
/// 是否不区分大小写, true为不区分, false为区分
///
判断结果
public static bool InArray(string strSearch, string[] stringArray, bool caseInsensetive)
{
return GetInArrayID(strSearch, stringArray, caseInsensetive) >= 0;
}
///
/// 判断指定字符串是否属于指定字符串数组中的一个元素
///
/// 字符串
/// 字符串数组
///
判断结果
public static bool InArray(string str, string[] stringarray)
{
return InArray(str, stringarray, false);
}
///
/// 判断指定字符串是否属于指定字符串数组中的一个元素
///
/// 字符串
/// 内部以逗号分割单词的字符串
///
判断结果
public static bool InArray(string str, string stringarray)
{
return InArray(str, SplitString(stringarray, ","), false);
}
///
/// 判断指定字符串是否属于指定字符串数组中的一个元素
///
/// 字符串
/// 内部以逗号分割单词的字符串
/// 分割字符串
///
判断结果
public static bool InArray(string str, string stringarray, string strsplit)
{
return InArray(str, SplitString(stringarray, strsplit), false);
}
///
/// 判断指定字符串是否属于指定字符串数组中的一个元素
///
/// 字符串
/// 内部以逗号分割单词的字符串
/// 分割字符串
/// 是否不区分大小写, true为不区分, false为区分
///
判断结果
public static bool InArray(string str, string stringarray, string strsplit, bool caseInsensetive)
{
return InArray(str, SplitString(stringarray, strsplit), caseInsensetive);
}
///
/// 删除字符串尾部的回车/换行/空格
///
///
///
public static string RTrim(string str)
{
for (int i = str.Length; i >= 0; i--)
{
if (str[i].Equals(" ") || str[i].Equals("/r") || str[i].Equals("/n"))
{
str.Remove(i, 1);
}
}
return str;
}
///
/// 清除给定字符串中的回车及换行符
///
/// 要清除的字符串
///
清除后返回的字符串
public static string ClearBR(string str)
{
Match m = null;
for (m = RegexBr.Match(str); m.Success; m = m.NextMatch())
{
str = str.Replace(m.Groups[0].ToString(), "");
}
return str;
}
///
/// 从字符串的指定位置截取指定长度的子字符串
///
/// 原字符串
/// 子字符串的起始位置
/// 子字符串的长度
///
子字符串
public static string CutString(string str, int startIndex, int length)
{
if (startIndex >= 0)
{
if (length < 0)
{
length = length * -1;
if (startIndex - length < 0)
{
length = startIndex;
startIndex = 0;
}
else
startIndex = startIndex - length;
}
if (startIndex > str.Length)
return "";
}
else
{
if (length < 0)
return "";
else
{
if (length + startIndex > 0)
{
length = length + startIndex;
startIndex = 0;
}
else
return "";
}
}
if (str.Length - startIndex < length)
length = str.Length - startIndex;
return str.Substring(startIndex, length);
}
///
/// 从字符串的指定位置开始截取到字符串结尾的了符串
///
/// 原字符串
/// 子字符串的起始位置
///
子字符串
public static string CutString(string str, int startIndex)
{
return CutString(str, startIndex, str.Length);
}
///
/// 获得当前绝对路径
///
/// 指定的路径,前面不要加/,从根开始
///
绝对路径
public static string GetMapPath(string strPath)
{
strPath = strPath.Replace("/", "//");
if (HttpContext.Current != null)
{
return System.IO.Path.Combine(HttpContext.Current.Server.MapPath("~"), strPath);
}
else //非web程序引用
{
if (strPath.StartsWith("//"))
{
strPath = strPath.Substring(strPath.IndexOf('//', 1)).TrimStart('//');
}
return System.IO.Path.Combine(AppDomain.CurrentDomain.BaseDirectory, strPath);
}
}
///
/// 返回文件是否存在
///
/// 文件名
///
是否存在
public static bool FileExists(string filename)
{
return System.IO.File.Exists(filename);
}
///
/// 以指定的ContentType输出指定文件文件
///
/// 文件路径
/// 输出的文件名
/// 将文件输出时设置的ContentType
public static void ResponseFile(string filepath, string filename, string filetype)
{
Stream iStream = null;
// 缓冲区为k
byte[] buffer = new Byte[10000];
// 文件长度
int length;
// 需要读的数据长度
long dataToRead;
try
{
// 打开文件
iStream = new FileStream(filepath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
// 需要读的数据长度
dataToRead = iStream.Length;
HttpContext.Current.Response.ContentType = filetype;
HttpContext.Current.Response.AddHeader("Content-Disposition", "attachment;filename=" + UrlEncode(filename.Trim()).Replace("+", " "));
while (dataToRead > 0)
{
// 检查客户端是否还处于连接状态
if (HttpContext.Current.Response.IsClientConnected)
{
length = iStream.Read(buffer, 0, 10000);
HttpContext.Current.Response.OutputStream.Write(buffer, 0, length);
HttpContext.Current.Response.Flush();
buffer = new Byte[10000];
dataToRead = dataToRead - length;
}
else
{
// 如果不再连接则跳出死循环
dataToRead = -1;
}
}
}
catch (Exception ex)
{
HttpContext.Current.Response.Write("Error : " + ex.Message);
}
finally
{
if (iStream != null)
{
// 关闭文件
iStream.Close();
}
}
HttpContext.Current.Response.End();
}
///
/// 判断文件名是否为浏览器可以直接显示的图片文件名
///
/// 文件名
///
是否可以直接显示
public static bool IsImgFilename(string filename)
{
filename = filename.Trim();
if (filename.EndsWith(".") || filename.IndexOf(".") == -1)
return false;
string extname = filename.Substring(filename.LastIndexOf(".") + 1).ToLower();
return (extname == "jpg" || extname == "jpeg" || extname == "png" || extname == "bmp" || extname == "gif");
}
///
/// int型转换为string型
///
///
转换后的string类型结果
public static string IntToStr(int intValue)
{
return Convert.ToString(intValue);
}
///
/// MD5函数
///
/// 原始字符串
///
MD5结果
public static string MD5(string str)
{
Byte[] clearBytes = new UnicodeEncoding().GetBytes(str);
Byte[] hashedBytes = ((HashAlgorithm)CryptoConfig.CreateFromName("MD5")).ComputeHash(clearBytes);
return BitConverter.ToString(hashedBytes).Replace("-", "").ToLower();
}
///
/// SHA256函数
///
/// /// 原始字符串
///
SHA256结果
public static string SHA256(string str)
{
byte[] SHA256Data = Encoding.UTF8.GetBytes(str);
SHA256Managed Sha256 = new SHA256Managed();
byte[] Result = Sha256.ComputeHash(SHA256Data);
return Convert.ToBase64String(Result); //返回长度为字节的字符串
}
///
/// 字符串如果操过指定长度则将超出的部分用指定字符串代替
///
/// 要检查的字符串
/// 指定长度
/// 用于替换的字符串
///
截取后的字符串
public static string GetSubString(string p_SrcString, int p_Length, string p_TailString)
{
return GetSubString(p_SrcString, 0, p_Length, p_TailString);
}
public static string GetUnicodeSubString(string str, int len, string p_TailString)
{
string result = string.Empty;// 最终返回的结果
int byteLen = System.Text.Encoding.Default.GetByteCount(str);// 单字节字符长度
int charLen = str.Length;// 把字符平等对待时的字符串长度
int byteCount = 0;// 记录读取进度
int pos = 0;// 记录截取位置
if (byteLen > len)
{
for (int i = 0; i < charLen; i++)
{
if (Convert.ToInt32(str.ToCharArray()[i]) > 255)// 按中文字符计算加
byteCount += 2;
else// 按英文字符计算加
byteCount += 1;
if (byteCount > len)// 超出时只记下上一个有效位置
{
pos = i;
break;
}
else if (byteCount == len)// 记下当前位置
{
pos = i + 1;
break;
}
}
if (pos >= 0)
result = str.Substring(0, pos) + p_TailString;
}
else
result = str;
return result;
}
///
/// 取指定长度的字符串
///
/// 要检查的字符串
/// 起始位置
/// 指定长度
/// 用于替换的字符串
///
截取后的字符串
public static string GetSubString(string p_SrcString, int p_StartIndex, int p_Length, string p_TailString)
{
string myResult = p_SrcString;
Byte[] bComments = Encoding.UTF8.GetBytes(p_SrcString);
foreach (char c in Encoding.UTF8.GetChars(bComments))
{ //当是日文或韩文时(注:中文的范围:/u4e00 - /u9fa5, 日文在/u0800 - /u4e00, 韩文为/xAC00-/xD7A3)
if ((c > '/u0800' && c < '/u4e00') || (c > '/xAC00' && c < '/xD7A3'))
{
//if (System.Text.RegularExpressions.Regex.IsMatch(p_SrcString, "[/u0800-/u4e00]+") || System.Text.RegularExpressions.Regex.IsMatch(p_SrcString, "[/xAC00-/xD7A3]+"))
//当截取的起始位置超出字段串长度时
if (p_StartIndex >= p_SrcString.Length)
return "";
else
return p_SrcString.Substring(p_StartIndex,
((p_Length + p_StartIndex) > p_SrcString.Length) ? (p_SrcString.Length - p_StartIndex) : p_Length);
}
}
if (p_Length >= 0)
{
byte[] bsSrcString = Encoding.Default.GetBytes(p_SrcString);
//当字符串长度大于起始位置
if (bsSrcString.Length > p_StartIndex)
{
int p_EndIndex = bsSrcString.Length;
//当要截取的长度在字符串的有效长度范围内
if (bsSrcString.Length > (p_StartIndex + p_Length))
{
p_EndIndex = p_Length + p_StartIndex;
}
else
{ //当不在有效范围内时,只取到字符串的结尾
p_Length = bsSrcString.Length - p_StartIndex;
p_TailString = "";
}
int nRealLength = p_Length;
int[] anResultFlag = new int[p_Length];
byte[] bsResult = null;
int nFlag = 0;
for (int i = p_StartIndex; i < p_EndIndex; i++)
{
if (bsSrcString[i] > 127)
{
nFlag++;
if (nFlag == 3)
nFlag = 1;
}
else
nFlag = 0;
anResultFlag[i] = nFlag;
}
if ((bsSrcString[p_EndIndex - 1] > 127) && (anResultFlag[p_Length - 1] == 1))
nRealLength = p_Length + 1;
bsResult = new byte[nRealLength];
Array.Copy(bsSrcString, p_StartIndex, bsResult, 0, nRealLength);
myResult = Encoding.Default.GetString(bsResult);
myResult = myResult + p_TailString;
}
}
return myResult;
}
///
/// 自定义的替换字符串函数
///
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);
}
///
/// 生成指定数量的html空格符号
///
public static string GetSpacesString(int spacesCount)
{
StringBuilder sb = new StringBuilder();
for (int i = 0; i < spacesCount; i++)
{
sb.Append(" ");
}
return sb.ToString();
}
///
/// 检测是否符合email格式
///
/// 要判断的email字符串
///
判断结果
public static bool IsValidEmail(string strEmail)
{
return Regex.IsMatch(strEmail, @"^[/w/.]+([-]/w+)*@[A-Za-z0-9-_]+[/.][A-Za-z0-9-_]");
}
public static bool IsValidDoEmail(string strEmail)
{
return Regex.IsMatch(strEmail, @"^@((/[[0-9]{1,3}/.[0-9]{1,3}/.[0-9]{1,3}/.)|(([/w-]+/.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(/]?)$");
}
///
/// 检测是否是正确的Url
///
/// 要验证的Url
///
判断结果
public static bool IsURL(string strUrl)
{
return Regex.IsMatch(strUrl, @"^(http|https)/://([a-zA-Z0-9/./-]+(/:[a-zA-Z0-9/.&%/$/-]+)*@)*((25[0-5]|2[0-4][0-9]|[0-1]{1}[0-9]{2}|[1-9]{1}[0-9]{1}|[1-9])/.(25[0-5]|2[0-4][0-9]|[0-1]{1}[0-9]{2}|[1-9]{1}[0-9]{1}|[1-9]|0)/.(25[0-5]|2[0-4][0-9]|[0-1]{1}[0-9]{2}|[1-9]{1}[0-9]{1}|[1-9]|0)/.(25[0-5]|2[0-4][0-9]|[0-1]{1}[0-9]{2}|[1-9]{1}[0-9]{1}|[0-9])|localhost|([a-zA-Z0-9/-]+/.)*[a-zA-Z0-9/-]+/.(com|edu|gov|int|mil|net|org|biz|arpa|info|name|pro|aero|coop|museum|[a-zA-Z]{1,10}))(/:[0-9]+)*(/($|[a-zA-Z0-9/./,/?/'///+&%/$#/=~_/-]+))*$");
}
public static string GetEmailHostName(string strEmail)
{
if (strEmail.IndexOf("@") < 0)
{
return "";
}
return strEmail.Substring(strEmail.LastIndexOf("@")).ToLower();
}
///
/// 判断是否为base64字符串
///
///
///
public static bool IsBase64String(string str)
{
//A-Z, a-z, 0-9, +, /, =
return Regex.IsMatch(str, @"[A-Za-z0-9/+///=]");
}
///
/// 检测是否有Sql危险字符
///
/// 要判断字符串
///
判断结果
public static bool IsSafeSqlString(string str)
{
return !Regex.IsMatch(str, @"[-|;|,|//|/(|/)|/[|/]|/}|/{|%|@|/*|!|/']");
}
///
/// 对查询字符串进行过滤
///
/// 要被过滤的查询字符串
///
过滤后的字符串
public static string SqlQueryEncode(string strKeyWords)
{
if (!System.String.IsNullOrEmpty(strKeyWords) && strKeyWords != "")
{
strKeyWords = strKeyWords.Replace("'", "");
strKeyWords = strKeyWords.Replace("[", "[[]");
strKeyWords = strKeyWords.Replace("_", "[_]");
strKeyWords = strKeyWords.Replace("&", "[&]");
strKeyWords = strKeyWords.Replace("#", "[#]");
strKeyWords = strKeyWords.Replace("%", "[%]");
}
return strKeyWords;
}
///
/// 对SqlQueryEncode函数过滤后的字符串进行还原
///
/// 经过SqlQueryEncode过滤后的字符串
///
还原后的字符串
public static string SqlQueryDecode(string strKeyWords)
{
if (!System.String.IsNullOrEmpty(strKeyWords) && strKeyWords != "")
{
strKeyWords = strKeyWords.Replace("[[]", "[");
strKeyWords = strKeyWords.Replace("[_]", "_");
strKeyWords = strKeyWords.Replace("[&]", "&");
strKeyWords = strKeyWords.Replace("[#]", "#");
strKeyWords = strKeyWords.Replace("[%]", "%");
}
return strKeyWords;
}
///
/// 对输入框的特殊字串进行过滤,防止SQL注入
///
/// 要被过滤的字符串
///
过滤后的字符串
public static string SqlInsertEncode(string strFromText)
{
if (!System.String.IsNullOrEmpty(strFromText) && strFromText != "")
{
strFromText = strFromText.Replace(";", ";");
strFromText = strFromText.Replace("!", "!");
//strFromText = strFromText.Replace("@", "@");
strFromText = strFromText.Replace("$", "$");
strFromText = strFromText.Replace("*", "*");
strFromText = strFromText.Replace("(", "(");
strFromText = strFromText.Replace(")", ")");
strFromText = strFromText.Replace("-", "-");
strFromText = strFromText.Replace("+", "+");
strFromText = strFromText.Replace("=", "=");
strFromText = strFromText.Replace("|", "|");
strFromText = strFromText.Replace("//", "\");
strFromText = strFromText.Replace("/", "/");
strFromText = strFromText.Replace(":", ":");
strFromText = strFromText.Replace("/"", """);
strFromText = strFromText.Replace("'", "'");
strFromText = strFromText.Replace("<", "<");
strFromText = strFromText.Replace(" ", " ");
strFromText = strFromText.Replace(">", ">");
strFromText = strFromText.Replace(" ", " ");
}
return strFromText;
}
///
/// 检测是否有危险的可能用于链接的字符串
///
/// 要判断字符串
///
判断结果
public static bool IsSafeUserInfoString(string str)
{
return !Regex.IsMatch(str, @"^/s*$|^c://con//con$|[%,/*" + "/"" + @"/s/t//&]|游客|^Guest");
}
///
/// 清理字符串
///
public static string CleanInput(string strIn)
{
return Regex.Replace(strIn.Trim(), @"[^/w/.@-]", "");
}
///
/// 返回URL中结尾的文件名
///
public static string GetFilename(string url)
{
if (url == null)
{
return "";
}
string[] strs1 = url.Split(new char[] { '/' });
return strs1[strs1.Length - 1].Split(new char[] { '?' })[0];
}
///
/// 根据阿拉伯数字返回月份的名称(可更改为某种语言)
///
public static string[] Monthes
{
get
{
return new string[] { "January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December" };
}
}
///
/// 替换回车换行符为html换行符
///
public static string StrFormat(string str)
{
string str2;
if (str == null)
{
str2 = "";
}
else
{
str = str.Replace("/r/n", "
");
str = str.Replace("/n", "
");
str2 = str;
}
return str2;
}
///
/// 返回标准日期格式string
///
public static string GetDate()
{
return DateTime.Now.ToString("yyyy-MM-dd");
}
///
/// 返回指定日期格式
///
public static string GetDate(string datetimestr, string replacestr)
{
if (datetimestr == null)
return replacestr;
if (datetimestr.Equals(""))
return replacestr;
try
{
datetimestr = Convert.ToDateTime(datetimestr).ToString("yyyy-MM-dd").Replace("1900-01-01", replacestr);
}
catch
{
return replacestr;
}
return datetimestr;
}
///
/// 返回标准时间格式string
///
public static string GetTime()
{
return DateTime.Now.ToString("HH:mm:ss");
}
///
/// 返回标准时间格式string
///
public static string GetDateTime()
{
return DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
}
///
/// 返回相对于当前时间的相对天数
///
public static string GetDateTime(int relativeday)
{
return DateTime.Now.AddDays(relativeday).ToString("yyyy-MM-dd HH:mm:ss");
}
///
/// 返回标准时间格式string
///
public static string GetDateTimeF()
{
return DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss:fffffff");
}
///
/// 返回标准时间
///
public static string GetStandardDateTime(string fDateTime, string formatStr)
{
if (fDateTime == "0000-0-0 0:00:00")
return fDateTime;
return Convert.ToDateTime(fDateTime).ToString(formatStr);
}
///
/// 返回标准时间yyyy-MM-dd HH:mm:ss
///
public static string GetStandardDateTime(string fDateTime)
{
return GetStandardDateTime(fDateTime, "yyyy-MM-dd HH:mm:ss");
}
/// /// 返回标准时间yyyy-MM-dd /// public static string GetStandardDate(string fDate) { return GetStandardDateTime(fDate, "yyyy-MM-dd"); } /// /// /// ///
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])?)$"); } /// /// 改正sql语句中的转义字符 /// public static string mashSQL(string str) { return (str == null) ? "" : str.Replace("/'", "'"); } /// /// 替换sql语句中的有问题符号 /// public static string ChkSQL(string str) { return (str == null) ? "" : str.Replace("'", "''"); } /// /// 转换为静态html /// public void transHtml(string path, string outpath) { Page page = new Page(); StringWriter writer = new StringWriter(); page.Server.Execute(path, writer); FileStream fs; if (File.Exists(page.Server.MapPath("") + "//" + outpath)) { File.Delete(page.Server.MapPath("") + "//" + outpath); fs = File.Create(page.Server.MapPath("") + "//" + outpath); } else { fs = File.Create(page.Server.MapPath("") + "//" + outpath); } byte[] bt = Encoding.Default.GetBytes(writer.ToString()); fs.Write(bt, 0, bt.Length); fs.Close(); } /// /// 转换为简体中文 /// public static string ToSChinese(string str) { return Strings.StrConv(str, VbStrConv.SimplifiedChinese, 0); } /// /// 转换为繁体中文 /// public static string ToTChinese(string str) { return Strings.StrConv(str, VbStrConv.TraditionalChinese, 0); } /// /// 分割字符串 /// public static string[] SplitString(string strContent, string strSplit) { if (!StrIsNullOrEmpty(strContent)) { if (strContent.IndexOf(strSplit) < 0) return new string[] { strContent }; return Regex.Split(strContent, Regex.Escape(strSplit), RegexOptions.IgnoreCase); } else return new string[0] { }; } /// /// 分割字符串 /// ///
public static string[] SplitString(string strContent, string strSplit, int count) { string[] result = new string[count]; string[] splited = SplitString(strContent, strSplit); for (int i = 0; i < count; i++) { if (i < splited.Length) result[i] = splited[i]; else result[i] = string.Empty; } return result; } /// /// 过滤字符串数组中每个元素为合适的大小 /// 当长度小于minLength时,忽略掉,-1为不限制最小长度 /// 当长度大于maxLength时,取其前maxLength位 /// 如果数组中有null元素,会被忽略掉 /// /// 单个元素最小长度 /// 单个元素最大长度 ///
public static string[] PadStringArray(string[] strArray, int minLength, int maxLength) { if (minLength > maxLength) { int t = maxLength; maxLength = minLength; minLength = t; } int iMiniStringCount = 0; for (int i = 0; i < strArray.Length; i++) { if (minLength > -1 && strArray[i].Length < minLength) { strArray[i] = null; continue; } if (strArray[i].Length > maxLength) strArray[i] = strArray[i].Substring(0, maxLength); iMiniStringCount++; } string[] result = new string[iMiniStringCount]; for (int i = 0, j = 0; i < strArray.Length && j < result.Length; i++) { if (strArray[i] != null && strArray[i] != string.Empty) { result[j] = strArray[i]; j++; } } return result; } /// /// 分割字符串 /// /// 被分割的字符串 /// 分割符 /// 忽略重复项 /// 单个元素最大长度 ///
public static string[] SplitString(string strContent, string strSplit, bool ignoreRepeatItem, int maxElementLength) { string[] result = SplitString(strContent, strSplit); return ignoreRepeatItem ? DistinctStringArray(result, maxElementLength) : result; } public static string[] SplitString(string strContent, string strSplit, bool ignoreRepeatItem, int minElementLength, int maxElementLength) { string[] result = SplitString(strContent, strSplit); if (ignoreRepeatItem) { result = DistinctStringArray(result); } return PadStringArray(result, minElementLength, maxElementLength); } /// /// 分割字符串 /// /// 被分割的字符串 /// 分割符 /// 忽略重复项 ///
public static string[] SplitString(string strContent, string strSplit, bool ignoreRepeatItem) { return SplitString(strContent, strSplit, ignoreRepeatItem, 0); } /// /// 清除字符串数组中的重复项 /// /// 字符串数组 /// 字符串数组中单个元素的最大长度 ///
public static string[] DistinctStringArray(string[] strArray, int maxElementLength) { Hashtable h = new Hashtable(); foreach (string s in strArray) { string k = s; if (maxElementLength > 0 && k.Length > maxElementLength) { k = k.Substring(0, maxElementLength); } h[k.Trim()] = s; } string[] result = new string[h.Count]; h.Keys.CopyTo(result, 0); return result; } /// /// 清除字符串数组中的重复项 /// /// 字符串数组 ///
public static string[] DistinctStringArray(string[] strArray) { return DistinctStringArray(strArray, 0); } /// /// 替换html字符 /// public static string EncodeHtml(string strHtml) { if (strHtml != "") { strHtml = strHtml.Replace(",", "&def"); strHtml = strHtml.Replace("'", "&dot"); strHtml = strHtml.Replace(";", "&dec"); return strHtml; } return ""; } /// /// 进行指定的替换(脏字过滤) /// public static string StrFilter(string str, string bantext) { string text1 = "", text2 = ""; string[] textArray1 = SplitString(bantext, "/r/n"); for (int num1 = 0; num1 < textArray1.Length; num1++) { text1 = textArray1[num1].Substring(0, textArray1[num1].IndexOf("=")); text2 = textArray1[num1].Substring(textArray1[num1].IndexOf("=") + 1); str = str.Replace(text1, text2); } return str; } /// /// 获得伪静态页码显示链接 /// /// 当前页数 /// 总页数 /// 超级链接地址 /// 周边页码显示个数上限 ///
页码html
public static string GetStaticPageNumbers(int curPage, int countPage, string url, string expname, int extendPage) { return GetStaticPageNumbers(curPage, countPage, url, expname, extendPage, 0); } /// /// 获得伪静态页码显示链接 /// /// 当前页数 /// 总页数 /// 超级链接地址 /// 周边页码显示个数上限 /// 当前版块是否使用URL重写 ///
页码html
public static string GetStaticPageNumbers(int curPage, int countPage, string url, string expname, int extendPage, int forumrewrite) { int startPage = 1; int endPage = 1; string t1 = "" + url + "-1" + expname + "/">«"; string t2 = "" + url + "-" + countPage + expname + "/">»"; if (forumrewrite == 1) { t1 = "" + url + "/1/list" + expname + "/">«"; t2 = "" + url + "/" + countPage + "/list" + expname + "/">»"; } if (forumrewrite == 2) { t1 = "" + url + "//">«"; t2 = "" + url + "/" + countPage + "//">»"; } if (countPage < 1) countPage = 1; if (extendPage < 3) extendPage = 2; if (countPage > extendPage) { if (curPage - (extendPage / 2) > 0) { if (curPage + (extendPage / 2) < countPage) { startPage = curPage - (extendPage / 2); endPage = startPage + extendPage - 1; } else { endPage = countPage; startPage = endPage - extendPage + 1; t2 = ""; } } else { endPage = extendPage; t1 = ""; } } else { startPage = 1; endPage = countPage; t1 = ""; t2 = ""; } StringBuilder s = new StringBuilder(""); s.Append(t1); for (int i = startPage; i <= endPage; i++) { if (i == curPage) { s.Append(""); s.Append(i); s.Append(""); } else { s.Append(""); if (forumrewrite == 1) { s.Append(url); if (i != 1) { s.Append("/"); s.Append(i); } s.Append("/list"); s.Append(expname); } else if (forumrewrite == 2) { s.Append(url); s.Append("/"); if (i != 1) { s.Append(i); s.Append("/"); } } else { s.Append(url); if (i != 1) { s.Append("-"); s.Append(i); } s.Append(expname); } s.Append("/">"); s.Append(i); s.Append(""); } } s.Append(t2); return s.ToString(); } /// /// 获得帖子的伪静态页码显示链接 /// /// /// 总页数 /// 超级链接地址 /// 周边页码显示个数上限 ///
页码html
public static string GetPostPageNumbers(int countPage, string url, string expname, int extendPage) { int startPage = 1; int endPage = 1; int curPage = 1; string t1 = "" + url + "-1" + expname + "/">«"; string t2 = "" + url + "-" + countPage + expname + "/">»"; if (countPage < 1) countPage = 1; if (extendPage < 3) extendPage = 2; if (countPage > extendPage) { if (curPage - (extendPage / 2) > 0) { if (curPage + (extendPage / 2) < countPage) { startPage = curPage - (extendPage / 2); endPage = startPage + extendPage - 1; } else { endPage = countPage; startPage = endPage - extendPage + 1; t2 = ""; } } else { endPage = extendPage; t1 = ""; } } else { startPage = 1; endPage = countPage; t1 = ""; t2 = ""; } StringBuilder s = new StringBuilder(""); s.Append(t1); for (int i = startPage; i <= endPage; i++) { s.Append(""); s.Append(url); s.Append("-"); s.Append(i); s.Append(expname); s.Append("/">"); s.Append(i); s.Append(""); } s.Append(t2); return s.ToString(); } /// /// 获得页码显示链接 /// /// 当前页数 /// 总页数 /// 超级链接地址 /// 周边页码显示个数上限 ///
页码html
public static string GetPageNumbers(int curPage, int countPage, string url, int extendPage) { return GetPageNumbers(curPage, countPage, url, extendPage, "page"); } /// /// 获得页码显示链接 /// /// 当前页数 /// 总页数 /// 超级链接地址 /// 周边页码显示个数上限 /// 页码标记 ///
页码html
public static string GetPageNumbers(int curPage, int countPage, string url, int extendPage, string pagetag) { return GetPageNumbers(curPage, countPage, url, extendPage, pagetag, null); } /// /// 获得页码显示链接 /// /// 当前页数 /// 总页数 /// 超级链接地址 /// 周边页码显示个数上限 /// 页码标记 /// 锚点 ///
页码html
public static string GetPageNumbers(int curPage, int countPage, string url, int extendPage, string pagetag, string anchor) { if (pagetag == "") pagetag = "page"; int startPage = 1; int endPage = 1; if (url.IndexOf("?") > 0) url = url + "&"; else url = url + "?"; string t1 = "" + url + "&" + pagetag + "=1"; string t2 = "" + url + "&" + pagetag + "=" + countPage; if (anchor != null) { t1 += anchor; t2 += anchor; } t1 += "/">«"; t2 += "/">»"; if (countPage < 1) countPage = 1; if (extendPage < 3) extendPage = 2; if (countPage > extendPage) { if (curPage - (extendPage / 2) > 0) { if (curPage + (extendPage / 2) < countPage) { startPage = curPage - (extendPage / 2); endPage = startPage + extendPage - 1; } else { endPage = countPage; startPage = endPage - extendPage + 1; t2 = ""; } } else { endPage = extendPage; t1 = ""; } } else { startPage = 1; endPage = countPage; t1 = ""; t2 = ""; } StringBuilder s = new StringBuilder(""); s.Append(t1); for (int i = startPage; i <= endPage; i++) { if (i == curPage) { s.Append(""); s.Append(i); s.Append(""); } else { s.Append(""); s.Append(url); s.Append(pagetag); s.Append("="); s.Append(i); if (anchor != null) { s.Append(anchor); } s.Append("/">"); s.Append(i); s.Append(""); } } s.Append(t2); return s.ToString(); } /// /// 返回HTML 字符串的编码结果 /// /// 字符串 ///
编码结果
public static string HtmlEncode(string str) { return HttpUtility.HtmlEncode(str); } /// /// 返回HTML 字符串的解码结果 /// /// 字符串 ///
解码结果
public static string HtmlDecode(string str) { return HttpUtility.HtmlDecode(str); } /// /// 返回URL 字符串的编码结果 /// /// 字符串 ///
编码结果
public static string UrlEncode(string str) { return HttpUtility.UrlEncode(str); } /// /// 返回URL 字符串的编码结果 /// /// 字符串 ///
解码结果
public static string UrlDecode(string str) { return HttpUtility.UrlDecode(str); } /// /// 返回指定目录下的非UTF8 字符集文件 /// /// 路径 ///
文件名的字符串数组
public static string[] FindNoUTF8File(string Path) { StringBuilder filelist = new StringBuilder(); DirectoryInfo Folder = new DirectoryInfo(Path); FileInfo[] subFiles = Folder.GetFiles(); for (int j = 0; j < subFiles.Length; j++) { if (subFiles[j].Extension.ToLower().Equals(".htm")) { FileStream fs = new FileStream(subFiles[j].FullName, FileMode.Open, FileAccess.Read); bool bUtf8 = IsUTF8(fs); fs.Close(); if (!bUtf8) { filelist.Append(subFiles[j].FullName); filelist.Append("/r/n"); } } } return SplitString(filelist.ToString(), "/r/n"); } //0000 0000-0000 007F - 0xxxxxxx (ascii converts to 1 octet!) //0000 0080-0000 07FF - 110xxxxx 10xxxxxx ( 2 octet format) //0000 0800-0000 FFFF - 1110xxxx 10xxxxxx 10xxxxxx (3 octet format) /// /// 判断文件流是否为UTF8字符集 /// /// 文件流 ///
判断结果
private static bool IsUTF8(FileStream sbInputStream) { int i; byte cOctets; // octets to go in this UTF-8 encoded character byte chr; bool bAllAscii = true; long iLen = sbInputStream.Length; cOctets = 0; for (i = 0; i < iLen; i++) { chr = (byte)sbInputStream.ReadByte(); if ((chr & 0x80) != 0) bAllAscii = false; if (cOctets == 0) { if (chr >= 0x80) { do { chr <<= 1; cOctets++; } while ((chr & 0x80) != 0); cOctets--; if (cOctets == 0) return false; } } else { if ((chr & 0xC0) != 0x80) return false; cOctets--; } } if (cOctets > 0) return false; if (bAllAscii) return false; return true; } /// /// 格式化字节数字符串 /// /// ///
public static string FormatBytesStr(int bytes) { if (bytes > 1073741824) return ((double)(bytes / 1073741824)).ToString("0") + "G"; if (bytes > 1048576) return ((double)(bytes / 1048576)).ToString("0") + "M"; if (bytes > 1024) return ((double)(bytes / 1024)).ToString("0") + "K"; return bytes.ToString() + "Bytes"; } /// /// 将long型数值转换为Int32类型 /// /// ///
public static int SafeInt32(object objNum) { if (objNum == null) return 0; string strNum = objNum.ToString(); if (IsNumeric(strNum)) { if (strNum.ToString().Length > 9) { if (strNum.StartsWith("-")) return int.MinValue; else return int.MaxValue; } return Int32.Parse(strNum); } else return 0; } /// /// 返回相差的秒数 /// /// /// ///
public static int StrDateDiffSeconds(string Time, int Sec) { TimeSpan ts = DateTime.Now - DateTime.Parse(Time).AddSeconds(Sec); if (ts.TotalSeconds > int.MaxValue) return int.MaxValue; else if (ts.TotalSeconds < int.MinValue) return int.MinValue; return (int)ts.TotalSeconds; } /// /// 返回相差的分钟数 /// /// /// ///
public static int StrDateDiffMinutes(string time, int minutes) { if (StrIsNullOrEmpty(time)) return 1; TimeSpan ts = DateTime.Now - DateTime.Parse(time).AddMinutes(minutes); if (ts.TotalMinutes > int.MaxValue) return int.MaxValue; else if (ts.TotalMinutes < int.MinValue) return int.MinValue; return (int)ts.TotalMinutes; } /// /// 返回相差的小时数 /// /// /// ///
public static int StrDateDiffHours(string time, int hours) { if (StrIsNullOrEmpty(time)) return 1; TimeSpan ts = DateTime.Now - DateTime.Parse(time).AddHours(hours); if (ts.TotalHours > int.MaxValue) return int.MaxValue; else if (ts.TotalHours < int.MinValue) return int.MinValue; return (int)ts.TotalHours; } /// /// 建立文件夹 /// /// ///
public static bool CreateDir(string name) { return MakeSureDirectoryPathExists(name); } /// /// 为脚本替换特殊字符串 /// /// ///
public static string ReplaceStrToScript(string str) { return str.Replace("//", "////").Replace("'", "//'").Replace("/"", "///""); } /// /// 是否为ip /// /// ///
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?|/*)$"); } /// /// 返回指定IP是否在指定的IP数组所限定的范围内, IP数组内的IP地址可以使用*表示该IP段任意, 例如.168.1.* /// /// /// ///
public static bool InIPArray(string ip, string[] iparray) { string[] userip = SplitString(ip, @"."); for (int ipIndex = 0; ipIndex < iparray.Length; ipIndex++) { string[] tmpip = 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; } /// /// 获得Assembly版本号 /// ///
public static string GetAssemblyVersion() { return string.Format("{0}.{1}.{2}", AssemblyFileVersion.FileMajorPart, AssemblyFileVersion.FileMinorPart, AssemblyFileVersion.FileBuildPart); } /// /// 获得Assembly产品名称 /// ///
public static string GetAssemblyProductName() { return AssemblyFileVersion.ProductName; } /// /// 获得Assembly产品版权 /// ///
public static string GetAssemblyCopyright() { return AssemblyFileVersion.LegalCopyright; } /// /// 创建目录 /// /// 名称 ///
创建是否成功
[DllImport("dbgHelp", SetLastError = true)] private static extern bool MakeSureDirectoryPathExists(string name); /// /// 判断字符串是否是yy-mm-dd字符串 /// /// 待判断字符串 ///
判断结果
public static bool IsDateString(string str) { return Regex.IsMatch(str, @"(/d{4})-(/d{1,2})-(/d{1,2})"); } /// /// 移除Html标记 /// /// ///
public static string RemoveHtml(string content) { return Regex.Replace(content, @"<[^>]*>", string.Empty, RegexOptions.IgnoreCase); } /// /// 过滤HTML中的不安全标签 /// /// ///
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; } /// /// 将用户组Title中的font标签去掉 /// /// 用户组Title ///
public static string RemoveFontTag(string title) { Match m = RegexFont.Match(title); if (m.Success) return m.Groups[1].Value; return title; } /// /// 判断对象是否为Int32类型的数字 /// /// ///
public static bool IsNumeric(string expression) { if (expression != null) { string str = expression; if (str.Length > 0 && str.Length <= 11 && Regex.IsMatch(str, @"^[-]?[0-9]*[.]?[0-9]*$")) { if ((str.Length < 10) || (str.Length == 10 && str[0] == '1') || (str.Length == 11 && str[0] == '-' && str[1] == '1')) return true; } } return false; } /// /// 是否为Double类型 /// /// ///
public static bool IsDouble(object expression) { if (expression != null) return Regex.IsMatch(expression.ToString(), @"^([0-9])[0-9]*(/./w*)?$"); return false; } /// /// 判断给定的字符串数组(strNumber)中的数据是不是都为数值型 /// /// 要确认的字符串数组 ///
是则返加true 不是则返回false
public static bool IsNumericArray(string[] strNumber) { if (strNumber == null) return false; if (strNumber.Length < 1) return false; foreach (string id in strNumber) { if (!IsNumeric(id)) return false; } return true; } /// /// 从HTML中获取文本,保留br,p,img /// /// ///
public static string GetTextFromHTML(string HTML) { System.Text.RegularExpressions.Regex regEx = new System.Text.RegularExpressions.Regex(@"
]*>", System.Text.RegularExpressions.RegexOptions.IgnoreCase); return regEx.Replace(HTML, ""); } /// /// string型转换为bool型 /// /// 要转换的字符串 /// 缺省值 ///
转换后的bool类型结果
public static bool StrToBool(object expression, bool defValue) { if (expression != null) return StrToBool(expression, defValue); return defValue; } /// /// string型转换为bool型 /// /// 要转换的字符串 /// 缺省值 ///
转换后的bool类型结果
public static bool StrToBool(string expression, bool defValue) { if (expression != null) { if (string.Compare(expression, "true", true) == 0) return true; else if (string.Compare(expression, "false", true) == 0) return false; } return defValue; } /// /// 将对象转换为Int32类型 /// /// 要转换的字符串 /// 缺省值 ///
转换后的int类型结果
public static int ObjectToInt(object expression) { return ObjectToInt(expression, 0); } /// /// 将对象转换为Int32类型 /// /// 要转换的字符串 /// 缺省值 ///
转换后的int类型结果
public static int ObjectToInt(object expression, int defValue) { if (expression != null) return StrToInt(expression.ToString(), defValue); return defValue; } /// /// 将对象转换为Int32类型,转换失败返回 /// /// 要转换的字符串 ///
转换后的int类型结果
public static int StrToInt(string str) { return StrToInt(str, 0); } /// /// 将对象转换为Int32类型 /// /// 要转换的字符串 /// 缺省值 ///
转换后的int类型结果
public static int StrToInt(string str, int defValue) { if (string.IsNullOrEmpty(str) || str.Trim().Length >= 11 || !Regex.IsMatch(str.Trim(), @"^([-]|[0-9])[0-9]*(/./w*)?$")) return defValue; int rv; if (Int32.TryParse(str, out rv)) return rv; return Convert.ToInt32(StrToFloat(str, defValue)); } /// /// string型转换为float型 /// /// 要转换的字符串 /// 缺省值 ///
转换后的int类型结果
public static float StrToFloat(object strValue, float defValue) { if ((strValue == null)) return defValue; return StrToFloat(strValue.ToString(), defValue); } /// /// string型转换为float型 /// /// 要转换的字符串 /// 缺省值 ///
转换后的int类型结果
public static float ObjectToFloat(object strValue, float defValue) { if ((strValue == null)) return defValue; return StrToFloat(strValue.ToString(), defValue); } /// /// string型转换为float型 /// /// 要转换的字符串 /// 缺省值 ///
转换后的int类型结果
public static float ObjectToFloat(object strValue) { return ObjectToFloat(strValue.ToString(), 0); } /// /// string型转换为float型 /// /// 要转换的字符串 ///
转换后的int类型结果
public static float StrToFloat(object strValue) { if ((strValue == null)) return 0; return StrToFloat(strValue.ToString(), 0); } /// /// string型转换为float型 /// /// 要转换的字符串 /// 缺省值 ///
转换后的int类型结果
public static float StrToFloat(string strValue, float defValue) { if ((strValue == null) || (strValue.Length > 10)) return defValue; float intValue = defValue; if (strValue != null) { bool IsFloat = Regex.IsMatch(strValue, @"^([-]|[0-9])[0-9]*(/./w*)?$"); if (IsFloat) float.TryParse(strValue, out intValue); } return intValue; } public static string AdDeTime(int times) { return (DateTime.Now).AddMinutes(times).ToString(); } /// /// 验证是否为正整数 /// /// ///
public static bool IsInt(string str) { return Regex.IsMatch(str, @"^[0-9]*$"); } public static bool IsRuleTip(Hashtable NewHash, string ruletype, out string key) { key = ""; foreach (DictionaryEntry str in NewHash) { try { string[] single = SplitString(str.Value.ToString(), "/r/n"); foreach (string strs in single) { if (strs != "") switch (ruletype.Trim().ToLower()) { case "email": if (IsValidDoEmail(strs.ToString()) == false) throw new Exception(); break; case "ip": if (IsIPSect(strs.ToString()) == false) throw new Exception(); break; case "timesect": string[] splitetime = strs.Split('-'); if (IsTime(splitetime[1].ToString()) == false || IsTime(splitetime[0].ToString()) == false) throw new Exception(); break; } } } catch { key = str.Key.ToString(); return false; } } return true; } /// /// 删除最后一个字符 /// /// ///
public static string ClearLastChar(string str) { return (str == "") ? "" : str.Substring(0, str.Length - 1); } /// /// 备份文件 /// /// 源文件名 /// 目标文件名 /// 当目标文件存在时是否覆盖 ///
操作是否成功
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; } } /// /// 备份文件,当目标文件存在时覆盖 /// /// 源文件名 /// 目标文件名 ///
操作是否成功
public static bool BackupFile(string sourceFileName, string destFileName) { return BackupFile(sourceFileName, destFileName, true); } /// /// 恢复文件 /// /// 备份文件名 /// 要恢复的文件名 /// 要恢复文件再次备份的名称,如果为null,则不再备份恢复文件 ///
操作是否成功
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); } /// /// 获取记录模板id的cookie名称 /// ///
public static string GetTemplateCookieName() { return TemplateCookieName; } /// /// 将全角数字转换为数字 /// /// ///
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); } /// /// 将字符串转换为Color /// /// ///
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); } } /// /// 转换长文件名为短文件名 /// /// /// /// /// /// ///
public static string ConvertSimpleFileName(string fullname, string repstring, int leftnum, int rightnum, int charnum) { string simplefilename = "", leftstring = "", rightstring = "", filename = ""; string extname = GetFileExtName(fullname); if (StrIsNullOrEmpty(extname)) throw new Exception("字符串不含有扩展名信息"); int filelength = 0, dotindex = 0; dotindex = fullname.LastIndexOf('.'); filename = fullname.Substring(0, dotindex); filelength = filename.Length; if (dotindex > charnum) { leftstring = filename.Substring(0, leftnum); rightstring = filename.Substring(filelength - rightnum, rightnum); if (repstring == "" || repstring == null) simplefilename = leftstring + rightstring + "." + extname; else simplefilename = leftstring + repstring + rightstring + "." + extname; } else simplefilename = fullname; return simplefilename; } //public static string GetFileExtName(string filename) //{ // string[] array = filename.Trim().Split('.'); // Array.Reverse(array); // return array[0].ToString(); //} /// /// 将数据表转换成JSON类型串 /// /// 要转换的数据表 ///
public static StringBuilder DataTableToJSON(System.Data.DataTable dt) { return DataTableToJson(dt, true); } /// /// 将数据表转换成JSON类型串 /// /// 要转换的数据表 /// 数据表转换结束后是否dispose掉 ///
public static StringBuilder DataTableToJson(System.Data.DataTable dt, bool dt_dispose) { StringBuilder stringBuilder = new StringBuilder(); stringBuilder.Append("[/r/n"); //数据表字段名和类型数组 string[] dt_field = new string[dt.Columns.Count]; int i = 0; string formatStr = "{{"; string fieldtype = ""; foreach (System.Data.DataColumn dc in dt.Columns) { dt_field[i] = dc.Caption.ToLower().Trim(); formatStr += "'" + dc.Caption.ToLower().Trim() + "':"; fieldtype = dc.DataType.ToString().Trim().ToLower(); if (fieldtype.IndexOf("int") > 0 || fieldtype.IndexOf("deci") > 0 || fieldtype.IndexOf("floa") > 0 || fieldtype.IndexOf("doub") > 0 || fieldtype.IndexOf("bool") > 0) { formatStr += "{" + i + "}"; } else { formatStr += "'{" + i + "}'"; } formatStr += ","; i++; } if (formatStr.EndsWith(",")) formatStr = formatStr.Substring(0, formatStr.Length - 1);//去掉尾部","号 formatStr += "}},"; i = 0; object[] objectArray = new object[dt_field.Length]; foreach (System.Data.DataRow dr in dt.Rows) { foreach (string fieldname in dt_field) { //对/ , ' 符号进行转换 objectArray[i] = dr[dt_field[i]].ToString().Trim().Replace("//", "////").Replace("'", "//'"); switch (objectArray[i].ToString()) { case "True": { objectArray[i] = "true"; break; } case "False": { objectArray[i] = "false"; break; } default: break; } i++; } i = 0; stringBuilder.Append(string.Format(formatStr, objectArray)); } if (stringBuilder.ToString().EndsWith(",")) stringBuilder.Remove(stringBuilder.Length - 1, 1);//去掉尾部","号 if (dt_dispose) dt.Dispose(); return stringBuilder.Append("/r/n];"); } /// /// 字段串是否为Null或为""(空) /// /// ///
public static bool StrIsNullOrEmpty(string str) { if (str == null || str.Trim() == string.Empty) return true; return false; } /// /// 是否为数值串列表,各数值间用","间隔 /// /// ///
public static bool IsNumericList(string numList) { if (StrIsNullOrEmpty(numList)) return false; return IsNumericArray(numList.Split(',')); } /// /// 检查颜色值是否为/6位的合法颜色 /// /// 待检查的颜色 ///
public static bool CheckColorValue(string color) { if (StrIsNullOrEmpty(color)) return false; color = color.Trim().Trim('#'); if (color.Length != 3 && color.Length != 6) return false; //不包含-9 a-f以外的字符 if (!Regex.IsMatch(color, "[^0-9a-f]", RegexOptions.IgnoreCase)) return true; return false; } /// /// 获取ajax形式的分页链接 /// /// 当前页数 /// 总页数 /// 回调函数 /// 周边页码显示个数上限 ///
public static string GetAjaxPageNumbers(int curPage, int countPage, string callback, int extendPage) { string pagetag = "page"; int startPage = 1; int endPage = 1; string t1 = "" + string.Format(callback, "&" + pagetag + "=1"); string t2 = "" + string.Format(callback, "&" + pagetag + "=" + countPage); t1 += "/">«"; t2 += "/">»"; if (countPage < 1) countPage = 1; if (extendPage < 3) extendPage = 2; if (countPage > extendPage) { if (curPage - (extendPage / 2) > 0) { if (curPage + (extendPage / 2) < countPage) { startPage = curPage - (extendPage / 2); endPage = startPage + extendPage - 1; } else { endPage = countPage; startPage = endPage - extendPage + 1; t2 = ""; } } else { endPage = extendPage; t1 = ""; } } else { startPage = 1; endPage = countPage; t1 = ""; t2 = ""; } StringBuilder s = new StringBuilder(""); s.Append(t1); for (int i = startPage; i <= endPage; i++) { if (i == curPage) { s.Append(""); s.Append(i); s.Append(""); } else { s.Append(""); s.Append(string.Format(callback, pagetag + "=" + i)); s.Append("/">"); s.Append(i); s.Append(""); } } s.Append(t2); return s.ToString(); } /// /// 根据Url获得源文件内容 /// /// 合法的Url地址 ///
public static string GetSourceTextByUrl(string url) { WebRequest request = WebRequest.Create(url); request.Timeout = 20000;//20秒超时 WebResponse response = request.GetResponse(); Stream resStream = response.GetResponseStream(); StreamReader sr = new StreamReader(resStream); return sr.ReadToEnd(); } /// /// 转换时间为unix时间戳 /// /// 需要传递UTC时间,避免时区误差,例:DataTime.UTCNow ///
public static double ConvertToUnixTimestamp(DateTime date) { DateTime origin = new DateTime(1970, 1, 1, 0, 0, 0, 0); TimeSpan diff = date - origin; return Math.Floor(diff.TotalSeconds); } /// /// Json特符字符过滤,参见http://www.json.org/ /// /// 要过滤的源字符串 ///
返回过滤的字符串
public static string JsonCharFilter(string sourceStr) { sourceStr = sourceStr.Replace("//", "////"); sourceStr = sourceStr.Replace("/b", "///b"); sourceStr = sourceStr.Replace("/t", "///t"); sourceStr = sourceStr.Replace("/n", "///n"); sourceStr = sourceStr.Replace("/n", "///n"); sourceStr = sourceStr.Replace("/f", "///f"); sourceStr = sourceStr.Replace("/r", "///r"); return sourceStr.Replace("/"", "///""); } /// /// 合并字符 /// /// 要合并的源字符串 /// 要被合并到的目的字符串 /// 合并符 ///
合并到的目的字符串
public static string MergeString(string source, string target) { return MergeString(source, target, ","); } /// /// 合并字符 /// /// 要合并的源字符串 /// 要被合并到的目的字符串 /// 合并符 ///
并到字符串
public static string MergeString(string source, string target, string mergechar) { if (StrIsNullOrEmpty(target)) target = source; else target += mergechar + source; return target; } /// /// 清除UBB标签 /// /// 帖子内容 ///
帖子内容
public static string ClearUBB(string sDetail) { return Regex.Replace(sDetail, @"/[[^/]]*?/]", string.Empty, RegexOptions.IgnoreCase); } /// /// 获取站点根目录URL /// ///
public static string GetRootUrl(string forumPath) { int port = HttpContext.Current.Request.Url.Port; return string.Format("{0}://{1}{2}{3}", HttpContext.Current.Request.Url.Scheme, HttpContext.Current.Request.Url.Host.ToString(), (port == 80 || port == 0) ? "" : ":" + port, forumPath); } /// /// 获取指定文件的扩展名 /// /// 指定文件名 ///
扩展名
public static string GetFileExtName(string fileName) { if (StrIsNullOrEmpty(fileName) || fileName.IndexOf('.') <= 0) return ""; fileName = fileName.ToLower().Trim(); return fileName.Substring(fileName.LastIndexOf('.'), fileName.Length - fileName.LastIndexOf('.')); } } }