using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Net;
using System.Web;
using System.Security.Cryptography;
using System.Text.RegularExpressions;
using System.Web.Script.Serialization;
using System.Data;
using System.Collections;
using System.Runtime.Serialization.Json;
using System.Configuration;
using System.Reflection;
namespace Ant.Service.Common
{
///
/// 系统帮助类
///
public class Utils
{
#region 对象转换处理
///
/// 判断对象是否为Int32类型的数字
///
///
///
public static bool IsNumeric(object expression)
{
if (expression != null)
return IsNumeric(expression.ToString());
return false;
}
///
/// 判断对象是否为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;
}
///
/// 将字符串转换为数组
///
/// 字符串
/// 字符串数组
public static string[] GetStrArray(string str)
{
return str.Split(new char[',']);
}
///
/// 将数组转换为字符串
///
/// List
/// 分隔符
/// String
public static string GetArrayStr(List list, string speater)
{
StringBuilder sb = new StringBuilder();
for (int i = 0; i < list.Count; i++)
{
if (i == list.Count - 1)
{
sb.Append(list[i]);
}
else
{
sb.Append(list[i]);
sb.Append(speater);
}
}
return sb.ToString();
}
///
/// object型转换为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 ObjToInt(object expression, int defValue)
{
if (expression != null)
return StrToInt(expression.ToString(), defValue);
return defValue;
}
///
/// 将字符串转换为Int32类型
///
/// 要转换的字符串
/// 缺省值
/// 转换后的int类型结果
public static int StrToInt(string expression, int defValue)
{
if (string.IsNullOrEmpty(expression) || expression.Trim().Length >= 11 || !Regex.IsMatch(expression.Trim(), @"^([-]|[0-9])[0-9]*(\.\w*)?$"))
return defValue;
int rv;
if (Int32.TryParse(expression, out rv))
return rv;
return Convert.ToInt32(StrToFloat(expression, defValue));
}
///
/// Object型转换为decimal型
///
/// 要转换的字符串
/// 缺省值
/// 转换后的decimal类型结果
public static decimal ObjToDecimal(object expression, decimal defValue)
{
if (expression != null)
return StrToDecimal(expression.ToString(), defValue);
return defValue;
}
///
/// string型转换为decimal型
///
/// 要转换的字符串
/// 缺省值
/// 转换后的decimal类型结果
public static decimal StrToDecimal(string expression, decimal defValue)
{
if ((expression == null) || (expression.Length > 10))
return defValue;
decimal intValue = defValue;
if (expression != null)
{
bool IsDecimal = Regex.IsMatch(expression, @"^([-]|[0-9])[0-9]*(\.\w*)?$");
if (IsDecimal)
decimal.TryParse(expression, out intValue);
}
return intValue;
}
///
/// Object型转换为float型
///
/// 要转换的字符串
/// 缺省值
/// 转换后的int类型结果
public static float ObjToFloat(object expression, float defValue)
{
if (expression != null)
return StrToFloat(expression.ToString(), defValue);
return defValue;
}
///
/// string型转换为float型
///
/// 要转换的字符串
/// 缺省值
/// 转换后的int类型结果
public static float StrToFloat(string expression, float defValue)
{
if ((expression == null) || (expression.Length > 10))
return defValue;
float intValue = defValue;
if (expression != null)
{
bool IsFloat = Regex.IsMatch(expression, @"^([-]|[0-9])[0-9]*(\.\w*)?$");
if (IsFloat)
float.TryParse(expression, out intValue);
}
return intValue;
}
///
/// 将对象转换为日期时间类型
///
/// 要转换的字符串
/// 缺省值
/// 转换后的int类型结果
public static DateTime StrToDateTime(string str, DateTime defValue)
{
if (!string.IsNullOrEmpty(str))
{
DateTime dateTime;
if (DateTime.TryParse(str, out dateTime))
return dateTime;
}
return defValue;
}
///
/// 将对象转换为日期时间类型
///
/// 要转换的字符串
/// 转换后的int类型结果
public static DateTime StrToDateTime(string str)
{
return StrToDateTime(str, DateTime.Now);
}
///
/// 将对象转换为日期时间类型
///
/// 要转换的对象
/// 转换后的int类型结果
public static DateTime ObjectToDateTime(object obj)
{
return StrToDateTime(obj.ToString());
}
///
/// 将对象转换为日期时间类型
///
/// 要转换的对象
/// 缺省值
/// 转换后的int类型结果
public static DateTime ObjectToDateTime(object obj, DateTime defValue)
{
return StrToDateTime(obj.ToString(), defValue);
}
///
/// 将对象转换为字符串
///
/// 要转换的对象
/// 转换后的string类型结果
public static string ObjectToStr(object obj)
{
if (obj == null)
return "";
return obj.ToString().Trim();
}
#endregion
#region 分割字符串
///
/// 分割字符串
///
public static string[] SplitString(string strContent, string strSplit)
{
if (!string.IsNullOrEmpty(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;
}
#endregion
#region 截取字符串
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 GetSubString(string p_SrcString, int p_StartIndex, int p_Length, string p_TailString)
{
string str = p_SrcString;
byte[] bytes = Encoding.UTF8.GetBytes(p_SrcString);
foreach (char ch in Encoding.UTF8.GetChars(bytes))
{
if (((ch > 'ࠀ') && (ch < '一')) || ((ch > 0xac00) && (ch < 0xd7a3)))
{
if (p_StartIndex >= p_SrcString.Length)
{
return "";
}
return p_SrcString.Substring(p_StartIndex, ((p_Length + p_StartIndex) > p_SrcString.Length) ? (p_SrcString.Length - p_StartIndex) : p_Length);
}
}
if (p_Length < 0)
{
return str;
}
byte[] sourceArray = Encoding.Default.GetBytes(p_SrcString);
if (sourceArray.Length <= p_StartIndex)
{
return str;
}
int length = sourceArray.Length;
if (sourceArray.Length > (p_StartIndex + p_Length))
{
length = p_Length + p_StartIndex;
}
else
{
p_Length = sourceArray.Length - p_StartIndex;
p_TailString = "";
}
int num2 = p_Length;
int[] numArray = new int[p_Length];
byte[] destinationArray = null;
int num3 = 0;
for (int i = p_StartIndex; i < length; i++)
{
if (sourceArray[i] > 0x7f)
{
num3++;
if (num3 == 3)
{
num3 = 1;
}
}
else
{
num3 = 0;
}
numArray[i] = num3;
}
if ((sourceArray[length - 1] > 0x7f) && (numArray[p_Length - 1] == 1))
{
num2 = p_Length + 1;
}
destinationArray = new byte[num2];
Array.Copy(sourceArray, p_StartIndex, destinationArray, 0, num2);
return (Encoding.Default.GetString(destinationArray) + p_TailString);
}
#endregion
#region 删除最后结尾的一个逗号
///
/// 删除最后结尾的一个逗号
///
public static string DelLastComma(string str)
{
return str.Substring(0, str.LastIndexOf(","));
}
#endregion
#region 删除最后结尾的指定字符后的字符
///
/// 删除最后结尾的指定字符后的字符
///
public static string DelLastChar(string str, string strchar)
{
if (string.IsNullOrEmpty(str))
return "";
if (str.LastIndexOf(strchar) >= 0 && str.LastIndexOf(strchar) == str.Length - 1)
{
return str.Substring(0, str.LastIndexOf(strchar));
}
return str;
}
#endregion
#region 生成指定长度的字符串
///
/// 生成指定长度的字符串,即生成strLong个str字符串
///
/// 生成的长度
/// 以str生成字符串
///
public static string StringOfChar(int strLong, string str)
{
string ReturnStr = "";
for (int i = 0; i < strLong; i++)
{
ReturnStr += str;
}
return ReturnStr;
}
#endregion
#region 生成日期随机码
///
/// 生成日期随机码
///
///
public static string GetRamCode()
{
#region
return DateTime.Now.ToString("yyyyMMddHHmmssffff");
#endregion
}
#endregion
#region 生成随机字母或数字
///
/// 生成随机数字
///
/// 生成长度
///
public static string Number(int Length)
{
return Number(Length, false);
}
///
/// 生成随机数字
///
/// 生成长度
/// 是否要在生成前将当前线程阻止以避免重复
///
public static string Number(int Length, bool Sleep)
{
if (Sleep)
System.Threading.Thread.Sleep(3);
string result = "";
System.Random random = new Random();
for (int i = 0; i < Length; i++)
{
result += random.Next(10).ToString();
}
return result;
}
///
/// 生成随机字母字符串(数字字母混和)
///
/// 待生成的位数
public static string GetCheckCode(int codeCount)
{
string str = string.Empty;
int rep = 0;
long num2 = DateTime.Now.Ticks + rep;
rep++;
Random random = new Random(((int)(((ulong)num2) & 0xffffffffL)) | ((int)(num2 >> rep)));
for (int i = 0; i < codeCount; i++)
{
char ch;
int num = random.Next();
if ((num % 2) == 0)
{
ch = (char)(0x30 + ((ushort)(num % 10)));
}
else
{
ch = (char)(0x41 + ((ushort)(num % 0x1a)));
}
str = str + ch.ToString();
}
return str;
}
///
/// 根据日期和随机码生成订单号
///
///
public static string GetOrderNumber()
{
string num = DateTime.Now.ToString("yyMMddHHmmss");//yyyyMMddHHmmssms
return num + Number(2).ToString();
}
private static int Next(int numSeeds, int length)
{
byte[] buffer = new byte[length];
System.Security.Cryptography.RNGCryptoServiceProvider Gen = new System.Security.Cryptography.RNGCryptoServiceProvider();
Gen.GetBytes(buffer);
uint randomResult = 0x0;//这里用uint作为生成的随机数
for (int i = 0; i < length; i++)
{
randomResult |= ((uint)buffer[i] << ((length - 1 - i) * 8));
}
return (int)(randomResult % numSeeds);
}
#endregion
#region 截取字符长度
///
/// 截取字符长度
///
/// 字符
/// 长度
///
public static string CutString(string inputString, int len)
{
if (string.IsNullOrEmpty(inputString))
return "";
inputString = DropHTML(inputString);
ASCIIEncoding ascii = new ASCIIEncoding();
int tempLen = 0;
string tempString = "";
byte[] s = ascii.GetBytes(inputString);
for (int i = 0; i < s.Length; i++)
{
if ((int)s[i] == 63)
{
tempLen += 2;
}
else
{
tempLen += 1;
}
try
{
tempString += inputString.Substring(i, 1);
}
catch
{
break;
}
if (tempLen > len)
break;
}
//如果截过则加上半个省略号
byte[] mybyte = System.Text.Encoding.Default.GetBytes(inputString);
if (mybyte.Length > len)
tempString += "…";
return tempString;
}
#endregion
#region 对象<-->JSON 4.0使用
///
/// 对象转JSON
///
/// 对象实体
/// 内容
/// json包
public static string ObjetcToJson(T t)
{
try
{
DataContractJsonSerializer json = new DataContractJsonSerializer(typeof(T));
string szJson = "";
using (MemoryStream stream = new MemoryStream())
{
json.WriteObject(stream, t);
szJson = Encoding.UTF8.GetString(stream.ToArray());
}
return szJson;
}
catch { return ""; }
}
///
/// Json包转对象
///
/// 对象
/// json包
/// 异常抛null
public static object JsonToObject(string jsonstring)
{
object result = null;
try
{
DataContractJsonSerializer json = new DataContractJsonSerializer(typeof(T));
using (MemoryStream stream = new MemoryStream(Encoding.UTF8.GetBytes(jsonstring)))
{
result = json.ReadObject(stream);
}
return result;
}
catch { return result; }
}
#endregion
#region 对象<-->JSON 2.0 使用litjson插件
///
/// 对象转JSON jsonData
///
///
///
///
//public static string ObjetcToJsonData(T t)
//{
// try
// {
// JsonData json = new JsonData(t);
// return json.ToJson();
// }
// catch
// {
// return "";
// }
//}
/////
///// 对象转JSON jsonMapper
/////
/////
/////
/////
//public static string ObjetcToJsonMapper(T t)
//{
// try
// {
// JsonData json = JsonMapper.ToJson(t);
// return json.ToJson();
// }
// catch
// {
// return "";
// }
//}
/////
///// json转对象 jsonMapper
/////
/////
/////
//public static object JsonToObject(string jsons)
//{
// try
// {
// JsonData jsonObject = JsonMapper.ToObject(jsons);
// return jsonObject;
// }
// catch { return null; }
//}
#endregion
#region DataTable<-->JSON
///
/// DataTable转为json
///
/// DataTable
/// json数据
public static string DataTableToJson(DataTable dt)
{
List> list = new List>();
foreach (DataRow dr in dt.Rows)
{
Dictionary result = new Dictionary();
foreach (DataColumn dc in dt.Columns)
{
result.Add(dc.ColumnName, dr[dc]);
}
list.Add(result);
}
return SerializeToJson(list);
}
///
/// 序列化对象为Json字符串
///
/// 要序列化的对象
/// 序列化对象的深度,默认为100
/// Json字符串
public static string SerializeToJson(object obj, int recursionLimit = 100)
{
try
{
JavaScriptSerializer serialize = new JavaScriptSerializer();
serialize.RecursionLimit = recursionLimit;
return serialize.Serialize(obj);
}
catch { return ""; }
}
///
/// json包转DataTable
///
///
///
public static DataTable JsonToDataTable(string jsons)
{
DataTable dt = new DataTable();
try
{
JavaScriptSerializer serialize = new JavaScriptSerializer();
serialize.MaxJsonLength = Int32.MaxValue;
ArrayList list = serialize.Deserialize(jsons);
if (list.Count > 0)
{
foreach (Dictionary item in list)
{
if (item.Keys.Count == 0)//无值返回空
{
return dt;
}
if (dt.Columns.Count == 0)//初始Columns
{
foreach (string current in item.Keys)
{
dt.Columns.Add(current, item[current].GetType());
}
}
DataRow dr = dt.NewRow();
foreach (string current in item.Keys)
{
dr[current] = item[current];
}
dt.Rows.Add(dr);
}
}
}
catch
{
return dt;
}
return dt;
}
#endregion
#region List<--->DataTable
///
/// DataTable转换泛型集合
///
///
///
///
public static List DataTableToList(DataTable table)
{
List list = new List();
T t = default(T);
PropertyInfo[] propertypes = null;
string tempName = string.Empty;
foreach (DataRow row in table.Rows)
{
t = Activator.CreateInstance();
propertypes = t.GetType().GetProperties();
foreach (PropertyInfo pro in propertypes)
{
tempName = pro.Name;
if (table.Columns.Contains(tempName))
{
object value = row[tempName];
if (!value.ToString().Equals(""))
{
pro.SetValue(t, value, null);
}
}
}
list.Add(t);
}
return list.Count == 0 ? null : list;
}
///
/// 将集合类转换成DataTable
///
/// 集合
/// DataTable
public static DataTable ListToDataTable(IList list)
{
DataTable result = new DataTable();
if (list != null && list.Count > 0)
{
PropertyInfo[] propertys = list[0].GetType().GetProperties();
foreach (PropertyInfo pi in propertys)
{
result.Columns.Add(pi.Name, pi.PropertyType);
}
for (int i = 0; i < list.Count; i++)
{
ArrayList tempList = new ArrayList();
foreach (PropertyInfo pi in propertys)
{
object obj = pi.GetValue(list[i], null);
tempList.Add(obj);
}
object[] array = tempList.ToArray();
result.LoadDataRow(array, true);
}
}
return result;
}
public static List ConvertTo(DataTable dt) where T : new()
{
if (dt == null) return null;
if (dt.Rows.Count <= 0) return null;
List list = new List();
try
{
List columnsName = new List();
foreach (DataColumn dataColumn in dt.Columns)
{
columnsName.Add(dataColumn.ColumnName);//得到所有的表头
}
list = dt.AsEnumerable().ToList().ConvertAll(row => GetObject(row, columnsName)); //转换
return list;
}
catch
{
return null;
}
}
public static T GetObject(DataRow row, List columnsName) where T : new()
{
T obj = new T();
try
{
string columnname = "";
string value = "";
PropertyInfo[] Properties = typeof(T).GetProperties();
foreach (PropertyInfo objProperty in Properties) //遍历T的属性
{
columnname = columnsName.Find(name => name.ToLower() == objProperty.Name.ToLower()); //寻找可以匹配的表头名称
if (!string.IsNullOrEmpty(columnname))
{
value = row[columnname].ToString();
if (!string.IsNullOrEmpty(value))
{
if (Nullable.GetUnderlyingType(objProperty.PropertyType) != null) //存在匹配的表头
{
value = row[columnname].ToString().Replace("$", "").Replace(",", ""); //从dataRow中提取数据
objProperty.SetValue(obj, Convert.ChangeType(value, Type.GetType(Nullable.GetUnderlyingType(objProperty.PropertyType).ToString())), null); //赋值操作
}
else
{
value = row[columnname].ToString().Replace("%", ""); //存在匹配的表头
objProperty.SetValue(obj, Convert.ChangeType(value, Type.GetType(objProperty.PropertyType.ToString())), null);//赋值操作
}
}
}
}
return obj;
}
catch
{
return obj;
}
}
///
/// 将泛型集合类转换成DataTable
///
/// 集合项类型
/// 集合
/// 需要返回的列的列名
/// 数据集(表)
public static DataTable ListToDataTable(IList list, params string[] propertyName)
{
List propertyNameList = new List();
if (propertyName != null)
propertyNameList.AddRange(propertyName);
DataTable result = new DataTable();
if (list != null && list.Count > 0)
{
PropertyInfo[] propertys = list[0].GetType().GetProperties();
foreach (PropertyInfo pi in propertys)
{
if (propertyNameList.Count == 0)
{
result.Columns.Add(pi.Name, pi.PropertyType);
}
else
{
if (propertyNameList.Contains(pi.Name))
result.Columns.Add(pi.Name, pi.PropertyType);
}
}
for (int i = 0; i < list.Count; i++)
{
ArrayList tempList = new ArrayList();
foreach (PropertyInfo pi in propertys)
{
if (propertyNameList.Count == 0)
{
object obj = pi.GetValue(list[i], null);
tempList.Add(obj);
}
else
{
if (propertyNameList.Contains(pi.Name))
{
object obj = pi.GetValue(list[i], null);
tempList.Add(obj);
}
}
}
object[] array = tempList.ToArray();
result.LoadDataRow(array, true);
}
}
return result;
}
#endregion
#region 清除HTML标记
public static string DropHTML(string Htmlstring)
{
if (string.IsNullOrEmpty(Htmlstring)) return "";
//删除脚本
Htmlstring = Regex.Replace(Htmlstring, @"", "", 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, @"