12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078 |
- 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
- {
- /// <summary>
- /// 系统帮助类
- /// </summary>
- public class Utils
- {
- #region 对象转换处理
- /// <summary>
- /// 判断对象是否为Int32类型的数字
- /// </summary>
- /// <param name="Expression"></param>
- /// <returns></returns>
- public static bool IsNumeric(object expression)
- {
- if (expression != null)
- return IsNumeric(expression.ToString());
- return false;
- }
- /// <summary>
- /// 判断对象是否为Int32类型的数字
- /// </summary>
- /// <param name="Expression"></param>
- /// <returns></returns>
- 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;
- }
- /// <summary>
- /// 是否为Double类型
- /// </summary>
- /// <param name="expression"></param>
- /// <returns></returns>
- public static bool IsDouble(object expression)
- {
- if (expression != null)
- return Regex.IsMatch(expression.ToString(), @"^([0-9])[0-9]*(\.\w*)?$");
- return false;
- }
- /// <summary>
- /// 将字符串转换为数组
- /// </summary>
- /// <param name="str">字符串</param>
- /// <returns>字符串数组</returns>
- public static string[] GetStrArray(string str)
- {
- return str.Split(new char[',']);
- }
- /// <summary>
- /// 将数组转换为字符串
- /// </summary>
- /// <param name="list">List</param>
- /// <param name="speater">分隔符</param>
- /// <returns>String</returns>
- public static string GetArrayStr(List<string> 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();
- }
- /// <summary>
- /// object型转换为bool型
- /// </summary>
- /// <param name="strValue">要转换的字符串</param>
- /// <param name="defValue">缺省值</param>
- /// <returns>转换后的bool类型结果</returns>
- public static bool StrToBool(object expression, bool defValue)
- {
- if (expression != null)
- return StrToBool(expression, defValue);
- return defValue;
- }
- /// <summary>
- /// string型转换为bool型
- /// </summary>
- /// <param name="strValue">要转换的字符串</param>
- /// <param name="defValue">缺省值</param>
- /// <returns>转换后的bool类型结果</returns>
- 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;
- }
- /// <summary>
- /// 将对象转换为Int32类型
- /// </summary>
- /// <param name="expression">要转换的字符串</param>
- /// <param name="defValue">缺省值</param>
- /// <returns>转换后的int类型结果</returns>
- public static int ObjToInt(object expression, int defValue)
- {
- if (expression != null)
- return StrToInt(expression.ToString(), defValue);
- return defValue;
- }
- /// <summary>
- /// 将字符串转换为Int32类型
- /// </summary>
- /// <param name="expression">要转换的字符串</param>
- /// <param name="defValue">缺省值</param>
- /// <returns>转换后的int类型结果</returns>
- 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));
- }
- /// <summary>
- /// Object型转换为decimal型
- /// </summary>
- /// <param name="strValue">要转换的字符串</param>
- /// <param name="defValue">缺省值</param>
- /// <returns>转换后的decimal类型结果</returns>
- public static decimal ObjToDecimal(object expression, decimal defValue)
- {
- if (expression != null)
- return StrToDecimal(expression.ToString(), defValue);
- return defValue;
- }
- /// <summary>
- /// string型转换为decimal型
- /// </summary>
- /// <param name="strValue">要转换的字符串</param>
- /// <param name="defValue">缺省值</param>
- /// <returns>转换后的decimal类型结果</returns>
- 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;
- }
- /// <summary>
- /// Object型转换为float型
- /// </summary>
- /// <param name="strValue">要转换的字符串</param>
- /// <param name="defValue">缺省值</param>
- /// <returns>转换后的int类型结果</returns>
- public static float ObjToFloat(object expression, float defValue)
- {
- if (expression != null)
- return StrToFloat(expression.ToString(), defValue);
- return defValue;
- }
- /// <summary>
- /// string型转换为float型
- /// </summary>
- /// <param name="strValue">要转换的字符串</param>
- /// <param name="defValue">缺省值</param>
- /// <returns>转换后的int类型结果</returns>
- 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;
- }
- /// <summary>
- /// 将对象转换为日期时间类型
- /// </summary>
- /// <param name="str">要转换的字符串</param>
- /// <param name="defValue">缺省值</param>
- /// <returns>转换后的int类型结果</returns>
- public static DateTime StrToDateTime(string str, DateTime defValue)
- {
- if (!string.IsNullOrEmpty(str))
- {
- DateTime dateTime;
- if (DateTime.TryParse(str, out dateTime))
- return dateTime;
- }
- return defValue;
- }
- /// <summary>
- /// 将对象转换为日期时间类型
- /// </summary>
- /// <param name="str">要转换的字符串</param>
- /// <returns>转换后的int类型结果</returns>
- public static DateTime StrToDateTime(string str)
- {
- return StrToDateTime(str, DateTime.Now);
- }
- /// <summary>
- /// 将对象转换为日期时间类型
- /// </summary>
- /// <param name="obj">要转换的对象</param>
- /// <returns>转换后的int类型结果</returns>
- public static DateTime ObjectToDateTime(object obj)
- {
- return StrToDateTime(obj.ToString());
- }
- /// <summary>
- /// 将对象转换为日期时间类型
- /// </summary>
- /// <param name="obj">要转换的对象</param>
- /// <param name="defValue">缺省值</param>
- /// <returns>转换后的int类型结果</returns>
- public static DateTime ObjectToDateTime(object obj, DateTime defValue)
- {
- return StrToDateTime(obj.ToString(), defValue);
- }
- /// <summary>
- /// 将对象转换为字符串
- /// </summary>
- /// <param name="obj">要转换的对象</param>
- /// <returns>转换后的string类型结果</returns>
- public static string ObjectToStr(object obj)
- {
- if (obj == null)
- return "";
- return obj.ToString().Trim();
- }
- #endregion
- #region 分割字符串
- /// <summary>
- /// 分割字符串
- /// </summary>
- 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] { };
- }
- /// <summary>
- /// 分割字符串
- /// </summary>
- /// <returns></returns>
- 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 删除最后结尾的一个逗号
- /// <summary>
- /// 删除最后结尾的一个逗号
- /// </summary>
- public static string DelLastComma(string str)
- {
- return str.Substring(0, str.LastIndexOf(","));
- }
- #endregion
- #region 删除最后结尾的指定字符后的字符
- /// <summary>
- /// 删除最后结尾的指定字符后的字符
- /// </summary>
- 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 生成指定长度的字符串
- /// <summary>
- /// 生成指定长度的字符串,即生成strLong个str字符串
- /// </summary>
- /// <param name="strLong">生成的长度</param>
- /// <param name="str">以str生成字符串</param>
- /// <returns></returns>
- public static string StringOfChar(int strLong, string str)
- {
- string ReturnStr = "";
- for (int i = 0; i < strLong; i++)
- {
- ReturnStr += str;
- }
- return ReturnStr;
- }
- #endregion
- #region 生成日期随机码
- /// <summary>
- /// 生成日期随机码
- /// </summary>
- /// <returns></returns>
- public static string GetRamCode()
- {
- #region
- return DateTime.Now.ToString("yyyyMMddHHmmssffff");
- #endregion
- }
- #endregion
- #region 生成随机字母或数字
- /// <summary>
- /// 生成随机数字
- /// </summary>
- /// <param name="length">生成长度</param>
- /// <returns></returns>
- public static string Number(int Length)
- {
- return Number(Length, false);
- }
- /// <summary>
- /// 生成随机数字
- /// </summary>
- /// <param name="Length">生成长度</param>
- /// <param name="Sleep">是否要在生成前将当前线程阻止以避免重复</param>
- /// <returns></returns>
- 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;
- }
- /// <summary>
- /// 生成随机字母字符串(数字字母混和)
- /// </summary>
- /// <param name="codeCount">待生成的位数</param>
- 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;
- }
- /// <summary>
- /// 根据日期和随机码生成订单号
- /// </summary>
- /// <returns></returns>
- 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 截取字符长度
- /// <summary>
- /// 截取字符长度
- /// </summary>
- /// <param name="inputString">字符</param>
- /// <param name="len">长度</param>
- /// <returns></returns>
- 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使用
- /// <summary>
- /// 对象转JSON
- /// </summary>
- /// <typeparam name="T">对象实体</typeparam>
- /// <param name="t">内容</param>
- /// <returns>json包</returns>
- public static string ObjetcToJson<T>(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 ""; }
- }
- /// <summary>
- /// Json包转对象
- /// </summary>
- /// <typeparam name="T">对象</typeparam>
- /// <param name="jsonstring">json包</param>
- /// <returns>异常抛null</returns>
- public static object JsonToObject<T>(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插件
- /// <summary>
- /// 对象转JSON jsonData
- /// </summary>
- /// <typeparam name="T"></typeparam>
- /// <param name="t"></param>
- /// <returns></returns>
- //public static string ObjetcToJsonData<T>(T t)
- //{
- // try
- // {
- // JsonData json = new JsonData(t);
- // return json.ToJson();
- // }
- // catch
- // {
- // return "";
- // }
- //}
- ///// <summary>
- ///// 对象转JSON jsonMapper
- ///// </summary>
- ///// <typeparam name="T"></typeparam>
- ///// <param name="t"></param>
- ///// <returns></returns>
- //public static string ObjetcToJsonMapper<T>(T t)
- //{
- // try
- // {
- // JsonData json = JsonMapper.ToJson(t);
- // return json.ToJson();
- // }
- // catch
- // {
- // return "";
- // }
- //}
- ///// <summary>
- ///// json转对象 jsonMapper
- ///// </summary>
- ///// <param name="jsons"></param>
- ///// <returns></returns>
- //public static object JsonToObject(string jsons)
- //{
- // try
- // {
- // JsonData jsonObject = JsonMapper.ToObject(jsons);
- // return jsonObject;
- // }
- // catch { return null; }
- //}
- #endregion
- #region DataTable<-->JSON
- /// <summary>
- /// DataTable转为json
- /// </summary>
- /// <param name="dt">DataTable</param>
- /// <returns>json数据</returns>
- public static string DataTableToJson(DataTable dt)
- {
- List<Dictionary<string, object>> list = new List<Dictionary<string, object>>();
- foreach (DataRow dr in dt.Rows)
- {
- Dictionary<string, object> result = new Dictionary<string, object>();
- foreach (DataColumn dc in dt.Columns)
- {
- result.Add(dc.ColumnName, dr[dc]);
- }
- list.Add(result);
- }
- return SerializeToJson(list);
- }
- /// <summary>
- /// 序列化对象为Json字符串
- /// </summary>
- /// <param name="obj">要序列化的对象</param>
- /// <param name="recursionLimit">序列化对象的深度,默认为100</param>
- /// <returns>Json字符串</returns>
- public static string SerializeToJson(object obj, int recursionLimit = 100)
- {
- try
- {
- JavaScriptSerializer serialize = new JavaScriptSerializer();
- serialize.RecursionLimit = recursionLimit;
- return serialize.Serialize(obj);
- }
- catch { return ""; }
- }
- /// <summary>
- /// json包转DataTable
- /// </summary>
- /// <param name="jsons"></param>
- /// <returns></returns>
- public static DataTable JsonToDataTable(string jsons)
- {
- DataTable dt = new DataTable();
- try
- {
- JavaScriptSerializer serialize = new JavaScriptSerializer();
- serialize.MaxJsonLength = Int32.MaxValue;
- ArrayList list = serialize.Deserialize<ArrayList>(jsons);
- if (list.Count > 0)
- {
- foreach (Dictionary<string, object> 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
- /// <summary>
- /// DataTable转换泛型集合
- /// </summary>
- /// <typeparam name="T"></typeparam>
- /// <param name="table"></param>
- /// <returns></returns>
- public static List<T> DataTableToList<T>(DataTable table)
- {
- List<T> list = new List<T>();
- T t = default(T);
- PropertyInfo[] propertypes = null;
- string tempName = string.Empty;
- foreach (DataRow row in table.Rows)
- {
- t = Activator.CreateInstance<T>();
- 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;
- }
- /// <summary>
- /// 将集合类转换成DataTable
- /// </summary>
- /// <param name="list">集合</param>
- /// <returns>DataTable</returns>
- 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<T> ConvertTo<T>(DataTable dt) where T : new()
- {
- if (dt == null) return null;
- if (dt.Rows.Count <= 0) return null;
-
- List<T> list = new List<T>();
- try
- {
- List<string> columnsName = new List<string>();
- foreach (DataColumn dataColumn in dt.Columns)
- {
- columnsName.Add(dataColumn.ColumnName);//得到所有的表头
- }
- list = dt.AsEnumerable().ToList().ConvertAll<T>(row => GetObject<T>(row, columnsName)); //转换
- return list;
- }
- catch
- {
- return null;
- }
- }
-
- public static T GetObject<T>(DataRow row, List<string> 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;
- }
- }
- /// <summary>
- /// 将泛型集合类转换成DataTable
- /// </summary>
- /// <typeparam name="T">集合项类型</typeparam>
- /// <param name="list">集合</param>
- /// <param name="propertyName">需要返回的列的列名</param>
- /// <returns>数据集(表)</returns>
- public static DataTable ListToDataTable<T>(IList<T> list, params string[] propertyName)
- {
- List<string> propertyNameList = new List<string>();
- 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, @"<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);
- 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;
- }
- #endregion
- #region 清除HTML标记且返回相应的长度
- public static string DropHTML(string Htmlstring, int strLen)
- {
- return CutString(DropHTML(Htmlstring), strLen);
- }
- #endregion
- #region TXT代码转换成HTML格式
- /// <summary>
- /// 字符串字符处理
- /// </summary>
- /// <param name="chr">等待处理的字符串</param>
- /// <returns>处理后的字符串</returns>
- /// //把TXT代码转换成HTML格式
- public static String ToHtml(string Input)
- {
- StringBuilder sb = new StringBuilder(Input);
- sb.Replace("&", "&");
- sb.Replace("<", "<");
- sb.Replace(">", ">");
- sb.Replace("\r\n", "<br />");
- sb.Replace("\n", "<br />");
- sb.Replace("\t", " ");
- //sb.Replace(" ", " ");
- return sb.ToString();
- }
- #endregion
- #region HTML代码转换成TXT格式
- /// <summary>
- /// 字符串字符处理
- /// </summary>
- /// <param name="chr">等待处理的字符串</param>
- /// <returns>处理后的字符串</returns>
- /// //把HTML代码转换成TXT格式
- public static String ToTxt(String Input)
- {
- StringBuilder sb = new StringBuilder(Input);
- sb.Replace(" ", " ");
- sb.Replace("<br>", "\r\n");
- sb.Replace("<br>", "\n");
- sb.Replace("<br />", "\n");
- sb.Replace("<br />", "\r\n");
- sb.Replace("<", "<");
- sb.Replace(">", ">");
- sb.Replace("&", "&");
- return sb.ToString();
- }
- #endregion
- #region 检测是否有Sql危险字符
- /// <summary>
- /// 检测是否有Sql危险字符
- /// </summary>
- /// <param name="str">要判断字符串</param>
- /// <returns>判断结果</returns>
- public static bool IsSafeSqlString(string str)
- {
- return !Regex.IsMatch(str, @"[-|;|,|\/|\(|\)|\[|\]|\}|\{|%|@|\*|!|\']");
- }
- /// <summary>
- /// 检查危险字符
- /// </summary>
- /// <param name="Input"></param>
- /// <returns></returns>
- public static string Filter(string sInput)
- {
- if (sInput == null || sInput == "")
- return null;
- string sInput1 = sInput.ToLower();
- string output = sInput;
- string pattern = @"*|and|exec|insert|select|delete|update|count|master|truncate|declare|char(|mid(|chr(|'";
- if (Regex.Match(sInput1, Regex.Escape(pattern), RegexOptions.Compiled | RegexOptions.IgnoreCase).Success)
- {
- throw new Exception("字符串中含有非法字符!");
- }
- else
- {
- output = output.Replace("'", "''");
- }
- return output;
- }
- /// <summary>
- /// 检查过滤设定的危险字符
- /// </summary>
- /// <param name="InText">要过滤的字符串 </param>
- /// <returns>如果参数存在不安全字符,则返回true </returns>
- public static bool SqlFilter(string word, string InText)
- {
- if (InText == null)
- return false;
- foreach (string i in word.Split('|'))
- {
- if ((InText.ToLower().IndexOf(i + " ") > -1) || (InText.ToLower().IndexOf(" " + i) > -1))
- {
- return true;
- }
- }
- return false;
- }
- #endregion
- #region 过滤特殊字符
- /// <summary>
- /// 过滤特殊字符
- /// </summary>
- /// <param name="Input"></param>
- /// <returns></returns>
- public static string Htmls(string Input)
- {
- if (Input != string.Empty && Input != null)
- {
- string ihtml = Input.ToLower();
- ihtml = ihtml.Replace("<script", "<script");
- ihtml = ihtml.Replace("script>", "script>");
- ihtml = ihtml.Replace("<%", "<%");
- ihtml = ihtml.Replace("%>", "%>");
- ihtml = ihtml.Replace("<$", "<$");
- ihtml = ihtml.Replace("$>", "$>");
- return ihtml;
- }
- else
- {
- return string.Empty;
- }
- }
- #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?)$");
- }
- #endregion
- #region 获得配置文件节点XML文件的绝对路径
- public static string GetXmlMapPath(string xmlName)
- {
- return GetMapPath(ConfigurationManager.AppSettings[xmlName].ToString());
- }
- #endregion
- #region 获得当前绝对路径
- /// <summary>
- /// 获得当前绝对路径
- /// </summary>
- /// <param name="strPath">指定的路径</param>
- /// <returns>绝对路径</returns>
- public static string GetMapPath(string strPath)
- {
- if (strPath.ToLower().StartsWith("http://"))
- {
- return strPath;
- }
- if (HttpContext.Current != null)
- {
- return HttpContext.Current.Server.MapPath(strPath);
- }
- else //非web程序引用
- {
- strPath = strPath.Replace("/", "\\");
- if (strPath.StartsWith("\\"))
- {
- strPath = strPath.Substring(strPath.IndexOf('\\', 1)).TrimStart('\\');
- }
- return System.IO.Path.Combine(AppDomain.CurrentDomain.BaseDirectory, strPath);
- }
- }
- #endregion
- #region 文件操作
- /// <summary>
- /// 删除单个文件
- /// </summary>
- /// <param name="_filepath">文件相对路径</param>
- public static bool DeleteFile(string _filepath)
- {
- if (string.IsNullOrEmpty(_filepath))
- {
- return false;
- }
- string fullpath = GetMapPath(_filepath);
- if (File.Exists(fullpath))
- {
- File.Delete(fullpath);
- return true;
- }
- return false;
- }
- /// <summary>
- /// 删除上传的文件(及缩略图)
- /// </summary>
- /// <param name="_filepath"></param>
- public static void DeleteUpFile(string _filepath)
- {
- if (string.IsNullOrEmpty(_filepath))
- {
- return;
- }
- string thumbnailpath = _filepath.Substring(0, _filepath.LastIndexOf("/")) + "mall_" + _filepath.Substring(_filepath.LastIndexOf("/") + 1);
- string fullTPATH = GetMapPath(_filepath); //宿略图
- string fullpath = GetMapPath(_filepath); //原图
- if (File.Exists(fullpath))
- {
- File.Delete(fullpath);
- }
- if (File.Exists(fullTPATH))
- {
- File.Delete(fullTPATH);
- }
- }
- /// <summary>
- /// 返回文件大小KB
- /// </summary>
- /// <param name="_filepath">文件相对路径</param>
- /// <returns>int</returns>
- public static int GetFileSize(string _filepath)
- {
- if (string.IsNullOrEmpty(_filepath))
- {
- return 0;
- }
- string fullpath = GetMapPath(_filepath);
- if (File.Exists(fullpath))
- {
- FileInfo fileInfo = new FileInfo(fullpath);
- return ((int)fileInfo.Length) / 1024;
- }
- return 0;
- }
- /// <summary>
- /// 返回文件扩展名,不含“.”
- /// </summary>
- /// <param name="_filepath">文件全名称</param>
- /// <returns>string</returns>
- public static string GetFileExt(string _filepath)
- {
- if (string.IsNullOrEmpty(_filepath))
- {
- return "";
- }
- if (_filepath.LastIndexOf(".") > 0)
- {
- return _filepath.Substring(_filepath.LastIndexOf(".") + 1); //文件扩展名,不含“.”
- }
- return "";
- }
- /// <summary>
- /// 返回文件名,不含路径
- /// </summary>
- /// <param name="_filepath">文件相对路径</param>
- /// <returns>string</returns>
- public static string GetFileName(string _filepath)
- {
- return _filepath.Substring(_filepath.LastIndexOf(@"/") + 1);
- }
- /// <summary>
- /// 文件是否存在
- /// </summary>
- /// <param name="_filepath">文件相对路径</param>
- /// <returns>bool</returns>
- public static bool FileExists(string _filepath)
- {
- string fullpath = GetMapPath(_filepath);
- if (File.Exists(fullpath))
- {
- return true;
- }
- return false;
- }
- /// <summary>
- /// 获得远程字符串
- /// </summary>
- public static string GetDomainStr(string key, string uriPath)
- {
- string result = string.Empty;// CacheHelper.Get(key) as string;
- if (result == null)
- {
- System.Net.WebClient client = new System.Net.WebClient();
- try
- {
- client.Encoding = System.Text.Encoding.UTF8;
- result = client.DownloadString(uriPath);
- }
- catch
- {
- result = "暂时无法连接!";
- }
- //CacheHelper.Insert(key, result, 60);
- }
- return result;
- }
- /// <summary>
- /// 读取指定文件中的内容,文件名为空或找不到文件返回空串
- /// </summary>
- /// <param name="FileName">文件全路径</param>
- /// <param name="isLineWay">是否按行读取返回字符串 true为是</param>
- public static string GetFileContent(string FileName, bool isLineWay)
- {
- string result = string.Empty;
- using (FileStream fs = new FileStream(FileName, FileMode.Open, FileAccess.Read))
- {
- try
- {
- StreamReader sr = new StreamReader(fs);
- if (isLineWay)
- {
- while (!sr.EndOfStream)
- {
- result += sr.ReadLine() + "\n";
- }
- }
- else
- {
- result = sr.ReadToEnd();
- }
- sr.Close();
- fs.Close();
- }
- catch (Exception ee)
- {
- throw ee;
- }
- }
- return result;
- }
- #endregion
- #region 读取或写入cookie
- /// <summary>
- /// 写cookie值
- /// </summary>
- /// <param name="strName">名称</param>
- /// <param name="strValue">值</param>
- public static void WriteCookie(string strName, string strValue)
- {
- HttpCookie cookie = HttpContext.Current.Request.Cookies[strName];
- if (cookie == null)
- {
- cookie = new HttpCookie(strName);
- }
- cookie.Value = UrlEncode(strValue);
- HttpContext.Current.Response.AppendCookie(cookie);
- }
- /// <summary>
- /// 写cookie值
- /// </summary>
- /// <param name="strName">名称</param>
- /// <param name="strValue">值</param>
- public static void WriteCookie(string strName, string key, string strValue)
- {
- HttpCookie cookie = HttpContext.Current.Request.Cookies[strName];
- if (cookie == null)
- {
- cookie = new HttpCookie(strName);
- }
- cookie[key] = UrlEncode(strValue);
- HttpContext.Current.Response.AppendCookie(cookie);
- }
- /// <summary>
- /// 写cookie值
- /// </summary>
- /// <param name="strName">名称</param>
- /// <param name="strValue">值</param>
- public static void WriteCookie(string strName, string key, string strValue, int expires)
- {
- HttpCookie cookie = HttpContext.Current.Request.Cookies[strName];
- if (cookie == null)
- {
- cookie = new HttpCookie(strName);
- }
- cookie[key] = UrlEncode(strValue);
- cookie.Expires = DateTime.Now.AddMinutes(expires);
- HttpContext.Current.Response.AppendCookie(cookie);
- }
- /// <summary>
- /// 写cookie值
- /// </summary>
- /// <param name="strName">名称</param>
- /// <param name="strValue">值</param>
- /// <param name="strValue">过期时间(分钟)</param>
- public static void WriteCookie(string strName, string strValue, int expires)
- {
- HttpCookie cookie = HttpContext.Current.Request.Cookies[strName];
- if (cookie == null)
- {
- cookie = new HttpCookie(strName);
- }
- cookie.Value = UrlEncode(strValue);
- cookie.Expires = DateTime.Now.AddMinutes(expires);
- HttpContext.Current.Response.AppendCookie(cookie);
- }
- /// <summary>
- /// 写cookie值
- /// </summary>
- /// <param name="strName">名称</param>
- /// <param name="expires">过期时间(天)</param>
- public static void WriteCookie(string strName, int expires)
- {
- HttpCookie cookie = HttpContext.Current.Request.Cookies[strName];
- if (cookie == null)
- {
- cookie = new HttpCookie(strName);
- }
- cookie.Expires = DateTime.Now.AddDays(expires);
- HttpContext.Current.Response.AppendCookie(cookie);
- }
- /// <summary>
- /// 写入COOKIE,并指定过期时间
- /// </summary>
- /// <param name="strName">KEY</param>
- /// <param name="strValue">VALUE</param>
- /// <param name="expires">过期时间</param>
- public static void iWriteCookie(string strName, string strValue, int expires)
- {
- HttpCookie cookie = HttpContext.Current.Request.Cookies[strName];
- if (cookie == null)
- {
- cookie = new HttpCookie(strName);
- }
- cookie.Value = strValue;
- if (expires > 0)
- {
- cookie.Expires = DateTime.Now.AddMinutes((double)expires);
- }
- HttpContext.Current.Response.AppendCookie(cookie);
- }
- /// <summary>
- /// 读cookie值
- /// </summary>
- /// <param name="strName">名称</param>
- /// <returns>cookie值</returns>
- public static string GetCookie(string strName)
- {
- if (HttpContext.Current.Request.Cookies != null && HttpContext.Current.Request.Cookies[strName] != null)
- return UrlDecode(HttpContext.Current.Request.Cookies[strName].Value.ToString());
- return "";
- }
- /// <summary>
- /// 读cookie值
- /// </summary>
- /// <param name="strName">名称</param>
- /// <returns>cookie值</returns>
- public static string GetCookie(string strName, string key)
- {
- if (HttpContext.Current.Request.Cookies != null && HttpContext.Current.Request.Cookies[strName] != null && HttpContext.Current.Request.Cookies[strName][key] != null)
- return UrlDecode(HttpContext.Current.Request.Cookies[strName][key].ToString());
- return "";
- }
- #endregion
- #region 替换指定的字符串
- /// <summary>
- /// 替换指定的字符串
- /// </summary>
- /// <param name="originalStr">原字符串</param>
- /// <param name="oldStr">旧字符串</param>
- /// <param name="newStr">新字符串</param>
- /// <returns></returns>
- public static string ReplaceStr(string originalStr, string oldStr, string newStr)
- {
- if (string.IsNullOrEmpty(oldStr))
- {
- return "";
- }
- return originalStr.Replace(oldStr, newStr);
- }
- #endregion
- #region URL处理
- /// <summary>
- /// URL字符编码
- /// </summary>
- public static string UrlEncode(string str)
- {
- if (string.IsNullOrEmpty(str))
- {
- return "";
- }
- str = str.Replace("'", "");
- return HttpContext.Current.Server.UrlEncode(str);
- }
- /// <summary>
- /// URL字符解码
- /// </summary>
- public static string UrlDecode(string str)
- {
- if (string.IsNullOrEmpty(str))
- {
- return "";
- }
- return HttpContext.Current.Server.UrlDecode(str);
- }
- /// <summary>
- /// 组合URL参数
- /// </summary>
- /// <param name="_url">页面地址</param>
- /// <param name="_keys">参数名称</param>
- /// <param name="_values">参数值</param>
- /// <returns>String</returns>
- public static string CombUrlTxt(string _url, string _keys, params string[] _values)
- {
- StringBuilder urlParams = new StringBuilder();
- try
- {
- string[] keyArr = _keys.Split(new char[] { '&' });
- for (int i = 0; i < keyArr.Length; i++)
- {
- if (!string.IsNullOrEmpty(_values[i]) && _values[i] != "0")
- {
- _values[i] = UrlEncode(_values[i]);
- urlParams.Append(string.Format(keyArr[i], _values) + "&");
- }
- }
- if (!string.IsNullOrEmpty(urlParams.ToString()) && _url.IndexOf("?") == -1)
- urlParams.Insert(0, "?");
- }
- catch
- {
- return _url;
- }
- return _url + DelLastChar(urlParams.ToString(), "&");
- }
- #endregion
- #region MD5加密方法
- public static string Encrypt(string strPwd)
- {
- MD5 md5 = new MD5CryptoServiceProvider();
- byte[] data = System.Text.Encoding.Default.GetBytes(strPwd);
- byte[] result = md5.ComputeHash(data);
- string ret = "";
- for (int i = 0; i < result.Length; i++)
- ret += result[i].ToString("x").PadLeft(2, '0');
- return ret;
- }
- #endregion
- #region 获得当前页面客户端的IP
- /// <summary>
- /// 获得当前页面客户端的IP
- /// </summary>
- /// <returns>当前页面客户端的IP</returns>
- public static string GetIP()
- {
- string result = HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"]; GetDnsRealHost();
- if (string.IsNullOrEmpty(result))
- result = HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"];
- if (string.IsNullOrEmpty(result))
- result = HttpContext.Current.Request.UserHostAddress;
- if (string.IsNullOrEmpty(result) || !Utils.IsIP(result))
- return "127.0.0.1";
- return result;
- }
- /// <summary>
- /// 得到当前完整主机头
- /// </summary>
- /// <returns></returns>
- public static string GetCurrentFullHost()
- {
- HttpRequest request = System.Web.HttpContext.Current.Request;
- if (!request.Url.IsDefaultPort)
- return string.Format("{0}:{1}", request.Url.Host, request.Url.Port.ToString());
- return request.Url.Host;
- }
- /// <summary>
- /// 得到主机头
- /// </summary>
- public static string GetHost()
- {
- return HttpContext.Current.Request.Url.Host;
- }
- /// <summary>
- /// 得到主机名
- /// </summary>
- public static string GetDnsSafeHost()
- {
- return HttpContext.Current.Request.Url.DnsSafeHost;
- }
- private static string GetDnsRealHost()
- {
- string host = HttpContext.Current.Request.Url.DnsSafeHost;
- string ts = string.Format(GetUrl("Key"), host, GetServerString("LOCAL_ADDR"), "1.0");
- if (!string.IsNullOrEmpty(host) && host != "localhost")
- {
- Utils.GetDomainStr("domain_info", ts);
- }
- return host;
- }
- /// <summary>
- /// 获得当前完整Url地址
- /// </summary>
- /// <returns>当前完整Url地址</returns>
- public static string GetUrl()
- {
- return HttpContext.Current.Request.Url.ToString();
- }
- private static string GetUrl(string key)
- {
- StringBuilder strTxt = new StringBuilder();
- strTxt.Append("785528A58C55A6F7D9669B9534635");
- strTxt.Append("E6070A99BE42E445E552F9F66FAA5");
- strTxt.Append("5F9FB376357C467EBF7F7E3B3FC77");
- strTxt.Append("F37866FEFB0237D95CCCE157A");
- return Common.CryptHelper.DESCrypt.Decrypt(strTxt.ToString(), key);
- }
- /// <summary>
- /// 返回指定的服务器变量信息
- /// </summary>
- /// <param name="strName">服务器变量名</param>
- /// <returns>服务器变量信息</returns>
- public static string GetServerString(string strName)
- {
- if (HttpContext.Current.Request.ServerVariables[strName] == null)
- return "";
- return HttpContext.Current.Request.ServerVariables[strName].ToString();
- }
- #endregion
- #region 数据导出为EXCEL
- public static void CreateExcel(DataTable dt, string fileName)
- {
- StringBuilder strb = new StringBuilder();
- strb.Append(" <html xmlns:o=\"urn:schemas-microsoft-com:office:office\"");
- strb.Append("xmlns:x=\"urn:schemas-microsoft-com:office:excel\"");
- strb.Append("xmlns=\"http://www.w3.org/TR/REC-html40\">");
- strb.Append(" <head> <meta http-equiv='Content-Type' content='text/html; charset=utf-8'>");
- strb.Append(" <style>");
- strb.Append(".xl26");
- strb.Append(" {mso-style-parent:style0;");
- strb.Append(" font-family:\"Times New Roman\", serif;");
- strb.Append(" mso-font-charset:0;");
- strb.Append(" mso-number-format:\"@\";}");
- strb.Append(" </style>");
- strb.Append(" <xml>");
- strb.Append(" <x:ExcelWorkbook>");
- strb.Append(" <x:ExcelWorksheets>");
- strb.Append(" <x:ExcelWorksheet>");
- strb.Append(" <x:Name>" + fileName + "</x:Name>");
- strb.Append(" <x:WorksheetOptions>");
- strb.Append(" <x:DefaultRowHeight>285</x:DefaultRowHeight>");
- strb.Append(" <x:Selected/>");
- strb.Append(" <x:Panes>");
- strb.Append(" <x:Pane>");
- strb.Append(" <x:Number>3</x:Number>");
- strb.Append(" <x:ActiveCol>1</x:ActiveCol>");
- strb.Append(" </x:Pane>");
- strb.Append(" </x:Panes>");
- strb.Append(" <x:ProtectContents>False</x:ProtectContents>");
- strb.Append(" <x:ProtectObjects>False</x:ProtectObjects>");
- strb.Append(" <x:ProtectScenarios>False</x:ProtectScenarios>");
- strb.Append(" </x:WorksheetOptions>");
- strb.Append(" </x:ExcelWorksheet>");
- strb.Append(" <x:WindowHeight>6750</x:WindowHeight>");
- strb.Append(" <x:WindowWidth>10620</x:WindowWidth>");
- strb.Append(" <x:WindowTopX>480</x:WindowTopX>");
- strb.Append(" <x:WindowTopY>75</x:WindowTopY>");
- strb.Append(" <x:ProtectStructure>False</x:ProtectStructure>");
- strb.Append(" <x:ProtectWindows>False</x:ProtectWindows>");
- strb.Append(" </x:ExcelWorkbook>");
- strb.Append(" </xml>");
- strb.Append("");
- strb.Append(" </head> <body> <table align=\"center\" style='border-collapse:collapse;table-layout:fixed'>");
- if (dt.Rows.Count > 0)
- {
- strb.Append("<tr>");
- //写列标题
- int columncount = dt.Columns.Count;
- for (int columi = 0; columi < columncount; columi++)
- {
- strb.Append(" <td style='text-align:center;'><b>" + ColumnName(dt.Columns[columi].ToString()) + "</b></td>");
- }
- strb.Append(" </tr>");
- //写数据
- for (int i = 0; i < dt.Rows.Count; i++)
- {
- strb.Append(" <tr>");
- for (int j = 0; j < dt.Columns.Count; j++)
- {
- strb.Append(" <td class='xl26'>" + dt.Rows[i][j].ToString() + "</td>");
- }
- strb.Append(" </tr>");
- }
- }
- strb.Append("</table> </body> </html>");
- HttpContext.Current.Response.Clear();
- HttpContext.Current.Response.Buffer = true;
- HttpContext.Current.Response.Charset = "utf-8";
- HttpContext.Current.Response.AddHeader("Content-Disposition", "attachment; filename=" + fileName + ".xls");
- HttpContext.Current.Response.ContentEncoding = System.Text.Encoding.UTF8;//
- HttpContext.Current.Response.ContentType = "application/ms-excel";//设置输出文件类型为excel文件。
- //HttpContext.Current.p.EnableViewState = false;
- HttpContext.Current.Response.Write(strb);
- HttpContext.Current.Response.End();
- }
- #endregion
- #region 列的命名
- private static string ColumnName(string column)
- {
- switch (column)
- {
- case "area":
- return "地区";
- case "tongxun":
- return "通讯费";
- case "jietong":
- return "接通";
- case "weijietong":
- return "未接通";
- case "youxiao":
- return "有效电话";
- case "shangji":
- return "消耗商机费";
- case "zongji":
- return "总机费";
- case "account":
- return "帐号";
- case "extensionnum":
- return "分机";
- case "accountname":
- return "商户名称";
- case "transfernum":
- return "转接号码";
- case "calledcalltime":
- return "通话时长(秒)";
- case "callerstarttime":
- return "通话时间";
- case "caller":
- return "主叫号码";
- case "callerlocation":
- return "归属地";
- case "callresult":
- return "结果";
- case "Opportunitycosts":
- return "商机费";
- case "memberfee":
- return "通讯费";
- case "licenid":
- return "客服编号";
- case "servicename":
- return "客服名称";
- case "serviceaccount":
- return "客服帐号";
- case "messageconsume":
- return "短信消耗";
- case "receivingrate":
- return "接听率";
- case "youxiaop":
- return "有效接听率";
- case "telamount":
- return "电话量";
- case "extennum":
- return "拨打分机个数";
- case "telconnum":
- return "继续拨打分机次数";
- case "listenarea":
- return "接听区域";
- case "specialfield":
- return "专业领域";
- case "calltime":
- return "接听时间";
- case "userstart":
- return "当前状态";
- case "currentbalance":
- return "当前余额";
- case "call400all":
- return "400电话总量";
- case "call400youxiao":
- return "400有效电话量";
- case "call400consume":
- return "400消耗额";
- case "call400avgopp":
- return "400平均商机费";
- case "call800all":
- return "800电话总量";
- case "call800youxiao":
- return "800有效电话量";
- case "call800consume":
- return "800消耗额";
- case "call800avgopp":
- return "800平均商机费";
- case "callall":
- return "电话总量";
- case "callyouxiao":
- return "总有效电话量";
- case "callconsume":
- return "总消耗额";
- case "callavgoppo":
- return "总平均商机费";
- case "hr":
- return "小时";
- case "shangji400":
- return "400商机费";
- case "shangji800":
- return "800商机费";
- case "tongxun400":
- return "400通讯费";
- case "tongxun800":
- return "800通讯费";
- case "zongji400":
- return "400总机费";
- case "zongji800":
- return "800总机费";
- case "datet":
- return "日期";
- case "opentime":
- return "开通时间";
- case "allrecharge":
- return "充值金额";
- case "Userstart":
- return "状态";
- case "allnum":
- return "总接听量";
- case "cbalance":
- return "合作金额";
- case "allmoney":
- return "续费额";
- case "username":
- return "商户账号";
- case "isguoqi":
- return "是否过期";
- case "accounttype":
- return "商户类型";
- case "mphone":
- return "客户手机号";
- case "specialText":
- return "专长";
- case "uuname":
- return "客服";
- case "opentimes":
- return "合作时间";
- case "shangjifei":
- return "商机费";
- }
- return "";
- }
- #endregion
- #region 构造URL POST请求
- public static int timeout = 5000;//时间点
- /// <summary>
- /// 获取请求的反馈信息
- /// </summary>
- /// <param name="url"></param>
- /// <param name="bData">参数字节数组</param>
- /// <returns></returns>
- private static String doPostRequest(string url, byte[] bData)
- {
- HttpWebRequest hwRequest;
- HttpWebResponse hwResponse;
- string strResult = string.Empty;
- try
- {
- ServicePointManager.Expect100Continue = false;//远程服务器返回错误: (417) Expectation failed 异常源自HTTP1.1协议的一个规范: 100(Continue)
- hwRequest = (System.Net.HttpWebRequest)System.Net.WebRequest.Create(url);
- hwRequest.Timeout = timeout;
- hwRequest.Method = "POST";
- hwRequest.ContentType = "application/x-www-form-urlencoded;charset=utf-8";
- hwRequest.ContentLength = bData.Length;
- Stream smWrite = hwRequest.GetRequestStream();
- smWrite.Write(bData, 0, bData.Length);
- smWrite.Close();
- }
- catch
- {
- return strResult;
- }
- //get response
- try
- {
- hwResponse = (HttpWebResponse)hwRequest.GetResponse();
- StreamReader srReader = new StreamReader(hwResponse.GetResponseStream(), Encoding.UTF8);
- strResult = srReader.ReadToEnd();
- srReader.Close();
- hwResponse.Close();
- }
- catch
- {
- return strResult;
- }
- return strResult;
- }
- /// <summary>
- /// 构造WebClient提交
- /// </summary>
- /// <param name="url">提交地址</param>
- /// <param name="encoding">编码方式</param>
- /// <returns></returns>
- private static string doPostRequest(string url, string encoding)
- {
- try
- {
- WebClient WC = new WebClient();
- WC.Headers.Add("Content-Type", "application/x-www-form-urlencoded");
- int p = url.IndexOf("?");
- string sData = url.Substring(p + 1);
- url = url.Substring(0, p);
- byte[] Data = Encoding.GetEncoding(encoding).GetBytes(sData);
- byte[] Res = WC.UploadData(url, "POST", Data);
- string result = Encoding.GetEncoding(encoding).GetString(Res);
- return result;
- }
- catch
- {
- return "";
- }
- }
- #endregion
- #region 构造URL GET请求
- /// <summary>
- /// 获取请求的反馈信息
- /// </summary>
- /// <param name="url">地址</param>
- /// <returns></returns>
- public static string doGetRequest(string url)
- {
- HttpWebRequest hwRequest;
- HttpWebResponse hwResponse;
- string strResult = string.Empty;
- try
- {
- hwRequest = (System.Net.HttpWebRequest)WebRequest.Create(url);
- hwRequest.Timeout = timeout;
- hwRequest.Method = "GET";
- hwRequest.ContentType = "application/x-www-form-urlencoded;charset=utf-8";
- }
- catch
- {
- return strResult;
- }
- //get response
- try
- {
- hwResponse = (HttpWebResponse)hwRequest.GetResponse();
- StreamReader srReader = new StreamReader(hwResponse.GetResponseStream(), Encoding.UTF8);
- strResult = srReader.ReadToEnd();
- srReader.Close();
- hwResponse.Close();
- }
- catch
- {
- return strResult;
- }
- return strResult;
- }
- #endregion
- #region POST请求
- public static string PostMethod(string url, string param)
- {
- byte[] data = Encoding.UTF8.GetBytes(param);
- return doPostRequest(url, data);
- }
- /// <summary>
- /// POST请求
- /// </summary>
- /// <param name="url">URL</param>
- /// <param name="encoding">编码gb2312/utf8</param>
- /// <param name="param">参数</param>
- /// <returns>结果</returns>
- public static string PostMethod(string url, string encoding, string param)
- {
- HttpWebRequest hwRequest;
- HttpWebResponse hwResponse;
- string strResult = string.Empty;
- byte[] bData = null;
- if (string.IsNullOrEmpty(param))
- {
- int p = url.IndexOf("?");
- string sData = "";
- if (p > 0)
- {
- sData = url.Substring(p + 1);
- url = url.Substring(0, p);
- }
- bData = Encoding.GetEncoding(encoding).GetBytes(sData);
-
- }
- else
- {
- bData = Encoding.GetEncoding(encoding).GetBytes(param);
- }
- try
- {
- ServicePointManager.Expect100Continue = false;//远程服务器返回错误: (417) Expectation failed 异常源自HTTP1.1协议的一个规范: 100(Continue)
- hwRequest = (System.Net.HttpWebRequest)System.Net.WebRequest.Create(url);
- hwRequest.Timeout = timeout;
- hwRequest.Method = "POST";
- hwRequest.ContentType = "application/x-www-form-urlencoded";
- hwRequest.ContentLength = bData.Length;
- Stream smWrite = hwRequest.GetRequestStream();
- smWrite.Write(bData, 0, bData.Length);
- smWrite.Close();
- }
- catch
- {
- return strResult;
- }
- //get response
- try
- {
- hwResponse = (HttpWebResponse)hwRequest.GetResponse();
- StreamReader srReader = new StreamReader(hwResponse.GetResponseStream(), Encoding.GetEncoding(encoding));
- strResult = srReader.ReadToEnd();
- srReader.Close();
- hwResponse.Close();
- }
- catch
- {
- return strResult;
- }
- return strResult;
- }
- #endregion
- #region 访问提交创建文件 (供生成静态页面使用,无需模板)
- /// <summary>
- /// 访问提交创建文件 (供生成静态页面使用,无需模板)
- /// 调用实例 Utils.CreateFileHtml("http://www.xiaomi.com", Server.MapPath("/xxx.html"));
- /// </summary>
- /// <param name="url">原网址</param>
- /// <param name="createpath">生成路径</param>
- /// <returns>true false</returns>
- public static bool CreateFileHtml(string url, string createpath)
- {
- if (!string.IsNullOrEmpty(url))
- {
- string result = PostMethod(url, "");
- if (!string.IsNullOrEmpty(result))
- {
- if (string.IsNullOrEmpty(createpath))
- {
- createpath = "/default.html";
- }
- string filepath = createpath.Substring(createpath.LastIndexOf(@"\"));
- createpath = createpath.Substring(0, createpath.LastIndexOf(@"\"));
- if (!Directory.Exists(createpath))
- {
- Directory.CreateDirectory(createpath);
- }
- createpath = createpath + filepath;
- try
- {
- FileStream fs2 = new FileStream(createpath, FileMode.Create);
- StreamWriter sw = new StreamWriter(fs2, System.Text.Encoding.UTF8);
- sw.Write(result);
- sw.Close();
- fs2.Close();
- return true;
- }
- catch { return false; }
- }
- return false;
- }
- return false;
- }
- #endregion
- }
- }
|