Mini.Crm/Mini.Common/Utility.cs

975 lines
35 KiB
C#
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

using System;
using System.Collections.Generic;
using System.Data;
using System.IO;
using System.Net;
using System.Reflection;
using System.Security.Cryptography;
using System.Text;
using System.Text.RegularExpressions;
using System.Web;
namespace Mini.Common
{
public static class Utility
{
/// <summary>
/// 获取配置文件中的设置
/// </summary>
/// <param name="key"></param>
/// <returns></returns>
public static string GetSettingByKey(string key)
{
return ConfigHelper.GetSectionValue(key);
}
/// <summary>
/// DataTable 转list
/// </summary>
/// <typeparam name="TResult"></typeparam>
/// <param name="dt"></param>
/// <returns></returns>
public static List<TResult> ToList<TResult>(this DataTable dt) where TResult : class, new()
{
//创建一个属性的列表
List<PropertyInfo> prlist = new List<PropertyInfo>();
//获取TResult的类型实例 反射的入口
Type t = typeof(TResult);
//获得TResult 的所有的Public 属性 并找出TResult属性和DataTable的列名称相同的属性(PropertyInfo) 并加入到属性列表
Array.ForEach<PropertyInfo>(t.GetProperties(), p => { if (dt.Columns.IndexOf(p.Name) != -1) prlist.Add(p); });
//创建返回的集合
List<TResult> oblist = new List<TResult>();
foreach (DataRow row in dt.Rows)
{
//创建TResult的实例
TResult ob = new TResult();
//找到对应的数据,并赋值
prlist.ForEach(p => { if (row[p.Name] != DBNull.Value) p.SetValue(ob, row[p.Name], null); });
//放入到返回的集合中.
oblist.Add(ob);
}
return oblist;
}
/// <summary>
/// List 转为DataTable
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="entitys"></param>
/// <returns></returns>
public static DataTable ToDataTable<T>(List<T> entitys)
{
//检查实体集合不能为空
if (entitys == null || entitys.Count < 1)
{
throw new Exception("需转换的集合为空");
}
//取出第一个实体的所有Propertie
Type entityType = entitys[0].GetType();
PropertyInfo[] entityProperties = entityType.GetProperties();
//生成DataTable的structure
//生产代码中应将生成的DataTable结构Cache起来此处略
DataTable dt = new DataTable();
for (int i = 0; i < entityProperties.Length; i++)
{
//dt.Columns.Add(entityProperties[i].Name, entityProperties[i].PropertyType);
dt.Columns.Add(entityProperties[i].Name);
}
//将所有entity添加到DataTable中
foreach (object entity in entitys)
{
//检查所有的的实体都为同一类型
if (entity.GetType() != entityType)
{
throw new Exception("要转换的集合元素类型不一致");
}
object[] entityValues = new object[entityProperties.Length];
for (int i = 0; i < entityProperties.Length; i++)
{
entityValues[i] = entityProperties[i].GetValue(entity, null);
}
dt.Rows.Add(entityValues);
}
return dt;
}
/// <summary>
/// List 转为DataTable需要指定类型
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="entitys"></param>
/// <returns></returns>
public static DataTable ToOracleDataTable<T>(List<T> entitys)
{
//检查实体集合不能为空
if (entitys == null || entitys.Count < 1)
{
throw new Exception("需转换的集合为空");
}
//取出第一个实体的所有Propertie
Type entityType = entitys[0].GetType();
PropertyInfo[] entityProperties = entityType.GetProperties();
//生成DataTable的structure
//生产代码中应将生成的DataTable结构Cache起来此处略
DataTable dt = new DataTable();
for (int i = 0; i < entityProperties.Length; i++)
{
Type colType = entityProperties[i].PropertyType;
if ((colType.IsGenericType) && (colType.GetGenericTypeDefinition() == typeof(Nullable<>)))
{
colType = colType.GetGenericArguments()[0];
}
dt.Columns.Add(entityProperties[i].Name, colType);
// dt.Columns.Add(entityProperties[i].Name);
}
//将所有entity添加到DataTable中
foreach (object entity in entitys)
{
//检查所有的的实体都为同一类型
if (entity.GetType() != entityType)
{
throw new Exception("要转换的集合元素类型不一致");
}
object[] entityValues = new object[entityProperties.Length];
for (int i = 0; i < entityProperties.Length; i++)
{
entityValues[i] = entityProperties[i].GetValue(entity, null);
}
dt.Rows.Add(entityValues);
}
return dt;
}
/// <summary>
/// List 转为DataTable需要指定类型
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="entitys"></param>
/// <returns></returns>
public static DataTable ToOracleDataTableToUpper<T>(List<T> entitys)
{
//检查实体集合不能为空
if (entitys == null || entitys.Count < 1)
{
throw new Exception("需转换的集合为空");
}
//取出第一个实体的所有Propertie
Type entityType = entitys[0].GetType();
PropertyInfo[] entityProperties = entityType.GetProperties();
//生成DataTable的structure
//生产代码中应将生成的DataTable结构Cache起来此处略
DataTable dt = new DataTable();
for (int i = 0; i < entityProperties.Length; i++)
{
Type colType = entityProperties[i].PropertyType;
if ((colType.IsGenericType) && (colType.GetGenericTypeDefinition() == typeof(Nullable<>)))
{
colType = colType.GetGenericArguments()[0];
}
dt.Columns.Add(entityProperties[i].Name.ToUpper(), colType);
// dt.Columns.Add(entityProperties[i].Name);
}
//将所有entity添加到DataTable中
foreach (object entity in entitys)
{
//检查所有的的实体都为同一类型
if (entity.GetType() != entityType)
{
throw new Exception("要转换的集合元素类型不一致");
}
object[] entityValues = new object[entityProperties.Length];
for (int i = 0; i < entityProperties.Length; i++)
{
entityValues[i] = entityProperties[i].GetValue(entity, null);
}
dt.Rows.Add(entityValues);
}
return dt;
}
/// <summary>
/// 把DataTable转成 List集合, 存每一行,集合中放的是键值对字典,存每一列
/// </summary>
/// <param name="dt">数据表</param>
/// <returns></returns>
public static List<Dictionary<string, object>> DataTableToList(DataTable dt)
{
List<Dictionary<string, object>> list = new List<Dictionary<string, object>>();
foreach (DataRow dr in dt.Rows)
{
Dictionary<string, object> dic = new Dictionary<string, object>();
foreach (DataColumn dc in dt.Columns)
{
dic.Add(dc.ColumnName, dr[dc.ColumnName].ToString());
}
list.Add(dic);
}
return list;
}
#region
// DES加密偏移量必须是>=8位长的字符串
private static string iv = "1234567890";
// DES加密的私钥必须是8位长的字符串DES
private static string key = "12345678";
/// <summary>
/// 对字符串加密后进行编码
/// </summary>
/// <param name="sourceString"></param>
/// <returns></returns>
public static string EncryptUrlEncode(string sourceString)
{
sourceString = Encrypt(sourceString);
return HttpUtility.UrlEncode(sourceString, Encoding.UTF8);
}
/// <summary>
/// 对字符串解码后解密
/// </summary>
/// <param name="sourceString"></param>
/// <returns></returns>
public static string DecryptUrlDecode(string sourceString)
{
if (sourceString.IndexOf("%") > -1)
sourceString = HttpUtility.UrlDecode(sourceString, Encoding.UTF8);
return Decrypt(sourceString);
}
/// <summary>
/// 对字符串进行DES加密
/// </summary>
/// <param name="sourceString">待加密的字符串</param>
/// <returns>加密后的BASE64编码的字符串</returns>
public static string Encrypt(string sourceString)
{
if (string.IsNullOrEmpty(sourceString))
{
return string.Empty;
}
else
{
byte[] btKey = Encoding.Default.GetBytes(key);
byte[] btIV = Encoding.Default.GetBytes(iv);
DESCryptoServiceProvider des = new DESCryptoServiceProvider();
using (MemoryStream ms = new MemoryStream())
{
byte[] inData = Encoding.Default.GetBytes(sourceString);
try
{
using (CryptoStream cs = new CryptoStream(ms, des.CreateEncryptor(btKey, btIV), CryptoStreamMode.Write))
{
cs.Write(inData, 0, inData.Length);
cs.FlushFinalBlock();
}
return Convert.ToBase64String(ms.ToArray());
}
catch (Exception ex)
{
throw ex;
}
}
}
}
/// <summary>
/// 对DES加密后的字符串进行解密
/// </summary>
/// <param name="encryptedString">待解密的字符串</param>
/// <returns>解密后的字符串</returns>
public static string Decrypt(string encryptedString)
{
if (string.IsNullOrEmpty(encryptedString))
{
return string.Empty;
}
else
{
byte[] btKey = Encoding.Default.GetBytes(key);
byte[] btIV = Encoding.Default.GetBytes(iv);
DESCryptoServiceProvider des = new DESCryptoServiceProvider();
using (MemoryStream ms = new MemoryStream())
{
byte[] inData = Convert.FromBase64String(encryptedString);
try
{
using (CryptoStream cs = new CryptoStream(ms, des.CreateDecryptor(btKey, btIV), CryptoStreamMode.Write))
{
cs.Write(inData, 0, inData.Length);
cs.FlushFinalBlock();
}
return Encoding.Default.GetString(ms.ToArray());
}
catch (Exception ex)
{
throw ex;
}
}
}
}
public static string Left(string sSource, int iLength)
{
return sSource.Substring(0, iLength > sSource.Length ? sSource.Length : iLength);
}
public static string Right(string sSource, int iLength)
{
return sSource.Substring(iLength > sSource.Length ? 0 : sSource.Length - iLength);
}
/// <summary>
/// md5加密
/// </summary>
/// <param name="message"></param>
/// <returns></returns>
public static string EncryptMD5(string input)
{
string output = null;
if (string.IsNullOrEmpty(input))
{
output = input;
}
else
{
MD5CryptoServiceProvider md5 = new MD5CryptoServiceProvider();
byte[] bytes = Encoding.UTF8.GetBytes(input);
string result = BitConverter.ToString(md5.ComputeHash(bytes));
return result.Replace("-", "");
}
return output;
}
/// <summary>
/// 进行DES解密。
/// </summary>
/// <param name="pToDecrypt">要解密的串</param>
/// <param name="sKey">密钥且必须为8位。</param>
/// <returns>已解密的字符串。</returns>
public static string DecryptDES(string source, string sKey)
{
byte[] inputByteArray = System.Convert.FromBase64String(source);//Encoding.UTF8.GetBytes(source);
using (DESCryptoServiceProvider des = new DESCryptoServiceProvider())
{
des.Mode = CipherMode.ECB;
des.Key = ASCIIEncoding.ASCII.GetBytes(sKey.Substring(0, 8));
des.IV = ASCIIEncoding.ASCII.GetBytes(sKey.Substring(0, 8));
System.IO.MemoryStream ms = new System.IO.MemoryStream();
using (CryptoStream cs = new CryptoStream(ms, des.CreateDecryptor(), CryptoStreamMode.Write))
{
cs.Write(inputByteArray, 0, inputByteArray.Length);
cs.FlushFinalBlock();
cs.Close();
}
string str = Encoding.UTF8.GetString(ms.ToArray());
ms.Close();
return str;
}
}
#endregion
/// <summary>
///时间格式化
/// </summary>
/// <param name="dt">返回字符串的类型(默认4)
///例子: 2014/05/08 19:14:17
///type=1 2014/05/08 没有时分秒
///type=2 2014/05/08 19:14 没有秒
///type=3 14/05/08 19:14 没有年前两位和秒
///type=4 05/08 19:14 没有年和秒
/// </param>
/// <returns></returns>
public static string ToUnityString(this DateTime dt, int type = 4)
{
if (dt == DateTime.MinValue)
return "";
string formartStr = string.Empty;
switch (type)
{
case 1: formartStr = "yyyy/MM/dd"; break;
case 2: formartStr = "yyyy/MM/dd HH:mm"; break;
case 3: formartStr = "yy/MM/dd HH:mm"; break;
case 4: formartStr = "MM/dd HH:mm"; break;
case 5: formartStr = "yyyyMM"; break;
case 6: formartStr = "yyyy-MM-dd"; break;
case 7: formartStr = "yyyy-MM-dd HH:mm:ss"; break;
}
return dt.ToString(formartStr);
}
/// <summary>
///时间格式化
/// </summary>
/// <param name="dt">返回字符串的类型(默认4)
///例子: 2014/05/08 19:14:17
///type=1 2014/05/08 没有时分秒
///type=2 2014/05/08 19:14 没有秒
///type=3 14/05/08 19:14 没有年前两位和秒
///type=4 05/08 19:14 没有年和秒
/// </param>
/// <returns></returns>
public static string ToUnityString(this DateTime? dt, int type = 4)
{
if (dt == null || dt.Value == DateTime.MinValue)
return "";
string formartStr = string.Empty;
switch (type)
{
case 1: formartStr = "yyyy/MM/dd"; break;
case 2: formartStr = "yyyy/MM/dd HH:mm"; break;
case 3: formartStr = "yy/MM/dd HH:mm"; break;
case 4: formartStr = "MM/dd HH:mm"; break;
case 5: formartStr = "yyyyMM"; break;
case 6: formartStr = "yyyy-MM-dd"; break;
}
return dt.Value.ToString(formartStr);
}
#region
public static string GetEnumName<T>(int i)
{
string name = null;
string[] names = Enum.GetNames(typeof(T));
if (i < names.Length)
{
name = names[i];
}
return name;
}
public static string GetEnumNameByValue<T>(int i)
{
string name = Enum.GetName(typeof(T), i);
return name;
}
public static string GetCheckEnumNameByValue<T>(int i)
{
string name = i.ToString();
if (Enum.IsDefined(typeof(T), i))
name = Enum.GetName(typeof(T), i);
return name;
}
#endregion
#region JSON
public static T JSONToObject<T>(string json)
{
return Newtonsoft.Json.JsonConvert.DeserializeObject<T>(json);
}
public static string ConvertToJSON<T>(IList<T> list)
{
return Newtonsoft.Json.JsonConvert.SerializeObject(list);
}
public static string ConvertToJSON<T>(T obj)
{
return Newtonsoft.Json.JsonConvert.SerializeObject(obj);
}
public static string ObjectToJson<T>(T t)
{
return Newtonsoft.Json.JsonConvert.SerializeObject(t);
}
#endregion
#region
static string[] SubstrSplit(string str, int lenStep)
{
if (string.IsNullOrEmpty(str))
return null;
int L = str.Length % lenStep;
if (L > 0)
{
for (int i = 0; i < lenStep - L; i++)
{
str = "0" + str;
}
}
string tem = "";
while (str.Length >= lenStep)
{
if (str.Length > lenStep)
tem += string.Format(",{0}", str.Substring(0, lenStep));
else
tem += string.Format(",{0}", str);
str = str.Substring(lenStep);
}
tem = tem.Trim(',');
return tem.Split(',');
}
public static string Conver10To64Ext(long d10)
{
string str64 = "";
string[] fhs = "0,1,2,3,4,5,6,7,8,9,@,-,a,b,c,d,e,f,g,h,i,j,k,l,m,n,o,p,q,r,s,t,u,v,w,x,y,z,A,B,C,D,E,F,G,H,I,J,K,L,M,N,O,P,Q,R,S,T,U,V,W,X,Y,Z".Split(',');
string binStr = Convert.ToString(d10, 2);
string[] bstrForLenStep = SubstrSplit(binStr, 6);
if (bstrForLenStep == null)
return "";
for (int j = 0; j < bstrForLenStep.Length; j++)
{
int index = Convert.ToInt32(bstrForLenStep[j], 2);
str64 += string.Format("{0}", fhs[index]);
}
return str64;
}
#endregion
#region unix
/// <summary>
/// 将Unix时间戳转换为DateTime类型时间
/// </summary>
/// <param name="d">double 型数字</param>
/// <returns>DateTime</returns>
public static System.DateTime ConvertIntDateTime(double d)
{
System.DateTime time = System.DateTime.MinValue;
System.DateTime startTime = TimeZone.CurrentTimeZone.ToLocalTime(new System.DateTime(1970, 1, 1));
time = startTime.AddSeconds(d);
return time;
}
/// <summary>
/// 将c# DateTime时间格式转换为Unix时间戳格式
/// </summary>
/// <param name="time">时间</param>
/// <returns>double</returns>
public static double ConvertDateTimeInt(System.DateTime time)
{
double intResult = 0;
System.DateTime startTime = TimeZone.CurrentTimeZone.ToLocalTime(new System.DateTime(1970, 1, 1));
intResult = (time - startTime).TotalSeconds;
return intResult;
}
/// <summary>
///
/// </summary>
/// <param name="timeJavaLong">java长整型日期毫秒为单位</param>
/// <returns></returns>
public static DateTime JavaLongToDateTime(long timeJavaLong)
{
var dt1970 = new DateTime(1970, 1, 1, 0, 0, 0);
var tricks1970 = dt1970.Ticks;//1970年1月1日刻度
var timeTricks = tricks1970 + timeJavaLong * 10000;//日志日期刻度
return new DateTime(timeTricks).AddHours(8);//转化为DateTime
}
#endregion
#region
/// <summary>
/// 00852+8位是香港的电话
/// </summary>
/// <param name="number"></param>
/// <returns></returns>
public static bool ChekMobile(string number)
{
string rgs = @"^(13|14|15|17|18|0085)\d{9}$";
Regex reg = new Regex(rgs);
return reg.IsMatch(number);
}
/// <summary>
/// 检查是否包含手机号码
/// </summary>
/// <param name="number"></param>
/// <returns></returns>
public static bool ContainMobile(string number)
{
string rgs = @".*(11|12|13|14|15|16|17|18|19)\d{9}.*";
Regex reg = new Regex(rgs);
return reg.IsMatch(number);
}
/// <summary>
/// 从文本中返回号码字符串
/// </summary>
/// <param name="txt"></param>
/// <returns></returns>
public static string GetMobile(string txt)
{
string rgs = @"(11|12|13|14|15|16|17|18|19)\d{9}";
string result = Regex.Match(txt, rgs).Value;
return result;
}
public static bool CheckIsNum(string txt)
{
string rgs = "^\\d{6,16}$";
Regex reg = new Regex(rgs);
return reg.IsMatch(txt);
}
public static bool IsNum(string txt)
{
string rgs = "^\\d+$";
Regex reg = new Regex(rgs);
return reg.IsMatch(txt);
}
#endregion
public static string NumberSub(string number)
{
string Sub_0 = @"^(013|015|016|018|014|017|019)\d*$";
Regex reg = new Regex(Sub_0);
if (number.Length > 11 && reg.IsMatch(number))
return number.Substring(1);
return number;
}
/// <summary>
/// 验证固定电话号码
/// </summary>
/// <param name="telcode"></param>
/// <returns></returns>
public static bool ValidateTelCode(string telcode)
{
string express = @"^(0[0-9]{2,3}\-?)?([2-9][0-9]{6,7})+(\-[0-9]{1,4})?$";
return ValidateInput(telcode, express);
}
public static string NumberFormat(string number)
{
if (string.IsNullOrEmpty(number) || number.Length <= 6)
{
return number;
}
return number.Substring(0, 3) +
new string('*', number.Length - 6) +
number.Substring(number.Length - 3);
}
/// <summary>
/// 验证固定电话号码无下滑斜杠
/// </summary>
/// <param name="telcode"></param>
/// <returns></returns>
public static bool ValidateTelCode2(string telcode)
{
string express = @"^\d{6,20}$";
return ValidateInput(telcode, express);
}
/// <summary>
/// 验证数据
/// </summary>
/// <param name="data">需验证数据</param>
/// <param name="express">正则表达式</param>
/// <returns>符合返回为true否则返回false</returns>
public static bool ValidateInput(string data, string express)
{
Regex reg = new Regex(express);
return reg.IsMatch(data);
}
/// <summary>
/// 获取随机数
/// </summary>
/// <param name="codeCount"></param>
/// <returns></returns>
public static string CreateRandomSatl(int codeCount)
{
string allChar = "0,1,2,3,4,5,6,7,8,9,A,B,C,D,E,F,G,H,I,J,K,L,M,N,O,P,Q,R,S,T,U,W,X,Y,Z,a,b,c,d,e,f,g,h,i,j,k,l,m,n,o,p,q,r,s,t,u,w,x,y,z";
string[] allCharArray = allChar.Split(',');
string randomCode = "";
int temp = -1;
Random rand = new Random();
for (int i = 0; i < codeCount; i++)
{
if (temp != -1)
{
rand = new Random(i * temp * ((int)DateTime.Now.Ticks));
}
int t = rand.Next(50);
if (temp == t)
{
return CreateRandomSatl(codeCount);
}
temp = t;
randomCode += allCharArray[t];
}
return randomCode;
}
public static string Sha512(string value)
{
SHA512 s512 = new SHA512Managed();
byte[] bit_pwd = Encoding.Default.GetBytes(value);
byte[] bit_shapsw = s512.ComputeHash(bit_pwd);
string shapsw = Convert.ToBase64String(bit_shapsw);
return shapsw;
}
public static int PasswordStrength(string password)
{
if (string.IsNullOrWhiteSpace(password)) return -1;
//字符统计
int iNum = 0, iLtt = 0, iSym = 0;
foreach (char c in password)
{
if (c >= '0' && c <= '9') iNum++;
else if (c >= 'a' && c <= 'z') iLtt++;
else if (c >= 'A' && c <= 'Z') iLtt++;
else iSym++;
}
if (password.Length < 6) return 3; //长度小于6的密码
if (iLtt == 0 && iSym == 0) return 1; //纯数字密码
if (iNum == 0 && iSym == 0) return 2; //纯字母密码
return 0; //正确
}
public static string GetSendMsgModel(string strJson, string modelParam)
{
string key = string.Empty;
string values = string.Empty;
strJson = strJson.Replace(",\"", "*\"").Replace("\":", "\"#").ToString();
Regex regex = new Regex(@"(?<={)[^}]+(?=})");
MatchCollection mc = regex.Matches(strJson);
Dictionary<string, string> list = new Dictionary<string, string>();
for (int i = 0; i < mc.Count; i++)
{
string strRow = mc[i].Value;
string[] strRows = strRow.Split('*');
foreach (string str in strRows)
{
string[] strCell = str.Split('#');
key = strCell[0].Replace("\"", "");
values = strCell[1].Replace("\"", "");
list.Add(key, values);
}
}
foreach (var item in list)
{
modelParam = modelParam.Replace("${" + item.Key + "}", item.Value);
}
return modelParam;
}
public static string DateEnToCn(string date)
{
string datename = "";
date = date.ToLower();
switch (date)
{//--Monday 周一 Tuesday 周二 Wednesday 周三 Thursday 周四 Friday 周五 Saturday 周六 Sunday 周日
case "monday": datename = "星期一"; break;
case "tuesday": datename = "星期二"; break;
case "wednesday": datename = "星期三"; break;
case "thursday": datename = "星期四"; break;
case "friday": datename = "星期五"; break;
case "saturday": datename = "星期六"; break;
case "sunday": datename = "星期日"; break;
}
return datename;
}
/// <summary>
/// 将c# DateTime时间格式转换为Unix时间戳格式
/// </summary>
/// <param name="time">时间</param>
/// <returns>long</returns>
public static long ConvertDateTimeToInt(System.DateTime time)
{
System.DateTime startTime = TimeZone.CurrentTimeZone.ToLocalTime(new System.DateTime(1970, 1, 1, 0, 0, 0, 0));
long t = (time.Ticks - startTime.Ticks) / 10000; //除10000调整为13位
return t;
}
/// <summary>
/// 时间戳转为C#格式时间
/// </summary>
/// <param name="timeStamp"></param>
/// <returns></returns>
public static DateTime ConvertStringToDateTime(string timeStamp)
{
DateTime dtStart = TimeZone.CurrentTimeZone.ToLocalTime(new DateTime(1970, 1, 1));
long lTime = long.Parse(timeStamp + "0000");
TimeSpan toNow = new TimeSpan(lTime);
return dtStart.Add(toNow);
}
/// <summary>
/// 获取文件的MD5码
/// </summary>
/// <param name="fileName">传入的文件名(含路径及后缀名)</param>
/// <returns></returns>
public static string GetMD5HashFromFile(string fileName)
{
try
{
FileStream file = new FileStream(fileName, System.IO.FileMode.Open);
MD5 md5 = new MD5CryptoServiceProvider();
byte[] retVal = md5.ComputeHash(file);
file.Close();
StringBuilder sb = new StringBuilder();
for (int i = 0; i < retVal.Length; i++)
{
sb.Append(retVal[i].ToString("x2"));
}
return sb.ToString();
}
catch (Exception ex)
{
throw new Exception("GetMD5HashFromFile() fail,error:" + ex.Message);
}
}
/// <summary>
/// 查找指定目录下的所有末级子目录
/// </summary>
/// <param name="dir">要查找的目录</param>
/// <param name="list">查找结果列表</param>
/// <param name="system">是否包含系统目录</param>
/// <param name="hidden">是否包含隐藏目录</param>
public static void GetEndDirectories(DirectoryInfo dir, List<DirectoryInfo> list, bool system = false, bool hidden = false)
{
DirectoryInfo[] sub = dir.GetDirectories();
if (sub.Length == 0)
{// 没有子目录了
list.Add(dir);
return;
}
foreach (DirectoryInfo subDir in sub)
{
// 跳过系统目录
if (!system && (subDir.Attributes & FileAttributes.System) == FileAttributes.System)
continue;
// 跳过隐藏目录
if (!hidden && (subDir.Attributes & FileAttributes.Hidden) == FileAttributes.Hidden)
continue;
GetEndDirectories(subDir, list);
}
}
/// <summary>
/// 获取数据
/// </summary>
/// <param name="url"></param>
/// <param name="encoding"></param>
/// <returns></returns>
public static string GetData(string Url, string RequestPara, Encoding encoding)
{
if (!String.IsNullOrEmpty(RequestPara))
RequestPara = RequestPara.IndexOf('?') > -1 ? (RequestPara) : ("?" + RequestPara);
WebRequest hr = HttpWebRequest.Create(Url + RequestPara);
byte[] buf = encoding.GetBytes(RequestPara);
hr.Method = "GET";
System.Net.WebResponse response = hr.GetResponse();
StreamReader reader = new StreamReader(response.GetResponseStream(), Encoding.GetEncoding("utf-8"));
string ReturnVal = reader.ReadToEnd();
reader.Close();
response.Close();
return ReturnVal;
}
/// <summary>
/// 获取数据
/// </summary>
/// <param name="url"></param>
/// <param name="encoding"></param>
/// <returns></returns>
public static List<string> GetArryData(string Url, string RequestPara, Encoding encoding)
{
if (!String.IsNullOrEmpty(RequestPara))
RequestPara = RequestPara.IndexOf('?') > -1 ? (RequestPara) : ("?" + RequestPara);
WebRequest hr = HttpWebRequest.Create(Url + RequestPara);
byte[] buf = encoding.GetBytes(RequestPara);
hr.Method = "GET";
List<string> htmllist = new List<string>();
System.Net.WebResponse response = hr.GetResponse();
using (StreamReader reader = new StreamReader(response.GetResponseStream(), Encoding.GetEncoding("utf-8")))
{
while (!reader.EndOfStream)
{
htmllist.Add(reader.ReadLine());
}
}
response.Close();
return htmllist;
}
/// <summary>
/// 获取数据
/// </summary>
/// <param name="url"></param>
/// <param name="encoding"></param>
/// <returns></returns>
public static string GetNewUrlData(string Url, string RequestPara, Encoding encoding)
{
if (!String.IsNullOrEmpty(RequestPara))
RequestPara = RequestPara.IndexOf('?') > -1 ? (RequestPara) : ("?" + RequestPara);
WebRequest hr = HttpWebRequest.Create(Url + RequestPara);
hr.Method = "GET";
System.Net.WebResponse response = hr.GetResponse();
string r= response.ResponseUri.AbsoluteUri;
response.Close();
return r;
}
/// <summary>
/// MD5 16位加密 加密后密码为小写
/// </summary>
/// <param name="ConvertString"></param>
/// <returns></returns>
public static string GetMd5Str16(string ConvertString)
{
try
{
using (MD5CryptoServiceProvider md5 = new MD5CryptoServiceProvider())
{
string t2 = BitConverter.ToString(md5.ComputeHash(UTF8Encoding.Default.GetBytes(ConvertString)), 4, 8);
return t2.Replace("-", "").ToLower();
}
}
catch { return null; }
}
}
}