using Api.Framework.Model;
using Api.Framework.SDK;
using CsharpHttpHelper;
using Api.Framework.Tools;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Configuration;
using System.Diagnostics;
using System.Drawing;
using System.Drawing.Imaging;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Runtime.ExceptionServices;
using System.Runtime.InteropServices;
using System.Runtime.Serialization.Formatters.Binary;
using System.Security.Cryptography;
using System.Text;
using System.Threading.Tasks;
using System.Web.Script.Serialization;
using System.Windows.Forms;
using ThoughtWorks.QRCode.Codec;
using ThoughtWorks.QRCode.Codec.Data;
using ZXing;
using static System.Net.Mime.MediaTypeNames;
using Image = System.Drawing.Image;
using System.Text.RegularExpressions;
using System.Net;
using System.Net.Mail;
using System.Net.Mime;
using Chat.Framework;
using System.Web.Caching;
using System.Web;
using System.Net.Http;
using Api.Framework.Utils;
using Newtonsoft.Json;
using System.ComponentModel;
using Newtonsoft.Json.Linq;
namespace Api.Framework.Tools
{
public class Util
{
///
/// 将数据转成对象
///
///
///
///
public static T ToObj(JToken data)
{
try
{
if (data == null)
return default(T);
//return JsonConvert.DeserializeObject(JsonConvert.SerializeObject(data));
return data.ToObject();
}
catch (Exception ex)
{
throw ex;
}
return default(T);
}
public static double ConvertDouble_FenToYuan(int value)
{
return (double)Math.Round((decimal.Parse(value.ToString()) / 100.0m), 2);
}
private static readonly object obj_Lock = new object();
///
/// 检测微信域名是否正常
///
///
///
public static async void CheckUrlDomain(string url, string noticeName = "")
{
if (ApiClient.Setting.SystemConfig.CheckUrlSwitch == Enums.SwitchType.关闭) return;
lock (obj_Lock)
{
try
{
if (string.IsNullOrWhiteSpace(url)) throw new Exception("url不能为空");
var wx = ChatClient.WXClient.Values.FirstOrDefault(f => f.Status == Chat.Framework.WXSdk.WxStatus.在线 && f.WeixinType == Chat.Framework.WXSdk.Implement.WeixinType.Hook微信);
if (wx != null)
{
if (!wx.CheckUrl(url))
{
Uri uri = new Uri(url);
var host = uri.Host;
if (!GetCache(host.ToLower()))
{
SetCache(host.ToLower(), 600);
var strb = new StringBuilder();
strb.AppendLine($@"域名监控通知:
中间页域名:{host},已被微信拦截,请及时更换");
ApiClient.SendNoticeMessage(strb.ToString(), noticeName);
}
}
}
}
catch (Exception ex)
{ }
}
}
///
/// 获取小程序xml文本
///
///
///
///
public static string GetMiNiAppXml(object data, ChatType chatType)
{
var xml = string.Empty;
try
{
if (data != null)
{
if (data is Dictionary)
{
var dic = data as Dictionary;
if (dic.ContainsKey("appId") && dic.ContainsKey("appName") && dic.ContainsKey("target"))
{
var appid = dic["appId"].ToString().Replace("\"", "");
var appname = dic["appName"].ToString().Replace("\"", "");
var target = dic["target"].ToString().Replace("\"", "");
switch (chatType)
{
case ChatType.微信:
{
#region 新
xml = $@"
view
33
0
0
0
0
308182020100047b30790201000204241402cf02032f53a102046aed7b7602046140580404546175706170706d73675f313964303238376430373335333963355f313633313630363738383235345f3737303538355f30663530663632362d316535632d343235352d613136352d6530316361333464353736300204011800030201000400
308ac8283026da65a796d699318d218c
12820
576
720
5951804402693f81eb27633f194a6a68
5951804402693f81eb27633f194a6a68
1
0
3
https://fd-1300509451.cos.ap-chengdu.myqcloud.com/fm1.jpeg
0
0
0
null
null
0
null
null
null
0
308ac8283026da65a796d699318d218c
2
0
0
720
576
0
0
0
0
0
0
";
#region xxx
// return $@"
//
//
//
// view
// 33
// 0
//
//
//
// 0
//
//
// 0
//
//
// 0
//
//
//
//
//
//
//
//
//
//
//
//
// 307f020100047830760201000204d6c63d1d02032f53a10204f0ed7b760204610f5d5304516175706170706d73675f323538663230643164323734356236655f313632383339363838333530365f3533335f61613163303962362d303134322d343032332d383862662d3935373136313536383462380204011800030201000400
// 308ac8283026da65a796d699318d218c
// 12820
// 576
// 720
// 0487c4db437f564f94d76fc32ca01cd5
// 0487c4db437f564f94d76fc32ca01cd5
// 1
//
// 0
//
//
// 3
// https://fd-1300509451.cos.ap-chengdu.myqcloud.com/fm1.jpeg
//
//
//
//
// 0
//
//
//
// 0
//
//
//
// 0
// null
// null
//
//
// 0
// null
// null
// null
//
// 0
//
//
//
//
//
//
//
//
// 308ac8283026da65a796d699318d218c
//
//
//
//
// 2
// 0
// 0
//
// 720
// 576
// 0
//
//
//
//
// 0
//
//
//
//
//
//
// 0
//
//
//
//
//
// 0
//
//
//
//
//
//
//
//
//
//
//
//
// 0
//
//
//
// 0
//
//
//";
#endregion
#endregion
return xml;
}
break;
case ChatType.企业微信:
{
}
break;
case ChatType.微信公众号:
case ChatType.未知来源:
case ChatType.QQ:
break;
default:
break;
}
}
}
}
}
catch (Exception ex)
{
}
finally
{
LogHelper.GetSingleObj().Debug("", $@"获取微信小程序文本:{JsonConvert.SerializeObject(data)}
平台:{chatType.ToString()}
xml:字符长度:{(string.IsNullOrWhiteSpace(xml) ? "0" : $"{xml.Length}")}");
}
return xml;
}
///
/// 缓存是否存在
///
///
///
///
///
public static bool GetCache(string text)
{
try
{
var MD5 = GetMD5($"{text}");
Cache cache = HttpRuntime.Cache;
object item = cache[MD5];
return item != null ? true : false;
}
catch (Exception)
{
}
return false;
}
///
/// 设置缓存(辅助输入)
///
///
///
///
///
public static bool SetCache(string text, int seconds = 60)
{
try
{
var MD5 = GetMD5($"{text}");
Cache cache = HttpRuntime.Cache;
//查找 md5 的缓存,不存在则返回null
object item = cache[MD5];
if (item == null)
cache.Insert(MD5, 1, null, DateTime.Now.AddSeconds(seconds), System.Web.Caching.Cache.NoSlidingExpiration);
return true;
}
catch (Exception ex)
{ }
return false;
}
///
/// 设置缓存(辅助输入)
///
///
///
///
///
public static void RemoveCache(string text)
{
try
{
var MD5 = GetMD5($"{text}");
Cache cache = HttpRuntime.Cache;
//查找 md5 的缓存,不存在则返回null
object item = cache[MD5];
if (item != null)
cache.Remove(MD5);
}
catch (Exception ex)
{ }
}
///
/// MD5字符串加密
///
///
/// 加密后字符串
public static string GetMD5(string txt)
{
using (MD5 mi = MD5.Create())
{
byte[] buffer = Encoding.Default.GetBytes(txt);
//开始加密
byte[] newBuffer = mi.ComputeHash(buffer);
StringBuilder sb = new StringBuilder();
for (int i = 0; i < newBuffer.Length; i++)
{
sb.Append(newBuffer[i].ToString("x2"));
}
return sb.ToString();
}
}
#region 读取配置文件
public static Dictionary ReadConfig(string name, bool refresh = false)
{
return Util.Read>(name);
}
#endregion
#region 二维码解析
[DllImport("PsyQrDcd.dll"), HandleProcessCorruptedStateExceptions]
private static extern int DecodePictureFile(string filename);
[DllImport("PsyQrDcd.dll"), HandleProcessCorruptedStateExceptions]
private static extern int GetDecodeData(int x, ref StringBuilder sb);
public static object _DecodePictureFile = new object();
private static Dictionary DecodeQRCodeCache = new Dictionary();
///
/// 二维码解析类型
///
public enum DecodeQRCodeType
{
全部 = 0,
Zxing = 1,
ThoughtWorks = 2,
Caoliao = 3,
}
///
/// 解密二维码
///
/// 文件路径
///
[HandleProcessCorruptedStateExceptions]
public static string DecodeQRCode(string filename, DecodeQRCodeType type = DecodeQRCodeType.Zxing)
{
if (!File.Exists(filename)) return string.Empty;
if (DecodeQRCodeCache.ContainsKey(filename)) return DecodeQRCodeCache[filename];
if (type == DecodeQRCodeType.Zxing || type == DecodeQRCodeType.全部)
{
//Zxing 解析二维码
try
{
using (var image = new Bitmap(filename))
{
BarcodeReader reader = new BarcodeReader();
System.Diagnostics.Stopwatch watch = new Stopwatch();
watch.Start();
Result result = reader.Decode(image); //通过reader解码
watch.Stop();
TimeSpan timeSpan = watch.Elapsed;
if (!string.IsNullOrEmpty(result.Text))
{
EventClient.OnEvent(null, $"Zxing 解析出二维码:" + result.Text);
DecodeQRCodeCache[filename] = result.Text;
return result.Text;
}
}
}
catch (Exception) { }
}
if (type == DecodeQRCodeType.ThoughtWorks || type == DecodeQRCodeType.全部)
{
//ThoughtWorks 解析二维码
try
{
using (var image = new Bitmap(filename))
{
string decodedString = new QRCodeDecoder().decode(new QRCodeBitmapImage(new Bitmap(filename)), Encoding.UTF8);
if (!string.IsNullOrEmpty(decodedString))
{
EventClient.OnEvent(null, $"ThoughtWorks 解析出二维码:" + decodedString);
DecodeQRCodeCache[filename] = decodedString;
return decodedString;
}
}
}
catch (Exception)
{ }
}
if (type == DecodeQRCodeType.Caoliao || type == DecodeQRCodeType.全部)
{
//草料解析
try
{
HttpHelper http = new HttpHelper();
string _name = filename.Substring(filename.LastIndexOf("\\") + 1); //文件名
StringBuilder sb = new StringBuilder("------WebKitFormBoundaryti0AVKw1aHIUR6yX\r\n");
sb.Append($"Content-Disposition: form-data; name=\"Filedata\"; filename=\"{_name}.jpg\"\r\n");
byte[] data = File.ReadAllBytes(filename);
var image = ReturnPhoto(data);
string content_type = GetMimeType(image);
sb.Append($"Content-Type: {content_type}\r\n");
sb.Append("\r\n");
var str = sb.ToString();
byte[] Header = Encoding.ASCII.GetBytes(sb.ToString());
byte[] Body = data;
byte[] Foot = Encoding.ASCII.GetBytes("\r\n------WebKitFormBoundaryti0AVKw1aHIUR6yX--\r\n");
var SendData = ComposeArrays(ComposeArrays(Header, Body), Foot);
var item = http.GetItem("https://upload.api.cli.im/upload.php?kid=cliim");
item.Header["Origin"] = "https://cli.im";
item.ContentType = "multipart/form-data; boundary=----WebKitFormBoundaryti0AVKw1aHIUR6yX";
item.Method = "post";
item.PostdataByte = SendData;
item.PostDataType = CsharpHttpHelper.Enum.PostDataType.Byte;
item.Referer = "https://cli.im/deqr";
var html = http.GetHtml(item).Html;
var json = HttpExtend.JsonToDictionary(html);
if (json["status"].ToString() == "1")
{
var json_data = json["data"] as Dictionary;
var upload_url = json_data["path"].ToString();
html = http.GetHtml("https://cli.im/apis/up/deqrimg", "", "img=" + HttpHelper.URLEncode(upload_url)).Html;
json = HttpExtend.JsonToDictionary(html);
if (json["status"].ToString() == "1" && json.ContainsKey("info"))
{
json_data = json["info"] as Dictionary;
if (json_data.ContainsKey("data"))
{
var list_url = json_data["data"] as ArrayList;
if (list_url.Count > 0)
{
var url = list_url[0].ToString();
EventClient.OnEvent(null, $"Api 解析出二维码:" + url);
DecodeQRCodeCache[filename] = url;
return url;
}
}
}
}
}
catch (Exception)
{ }
}
DecodeQRCodeCache[filename] = string.Empty;
return string.Empty;
}
public static System.Drawing.Image ReturnPhoto(byte[] streamByte)
{
System.IO.MemoryStream ms = new System.IO.MemoryStream(streamByte);
System.Drawing.Image img = System.Drawing.Image.FromStream(ms);
return img;
}
public static byte[] ComposeArrays(byte[] Array1, byte[] Array2)
{
byte[] Temp = new byte[Array1.Length + Array2.Length];
Array1.CopyTo(Temp, 0);
Array2.CopyTo(Temp, Array1.Length);
return Temp;
}
///
/// 通过FileStream 来打开文件,这样就可以实现不锁定Image文件,到时可以让多用户同时访问Image文件
///
///
///
public static Bitmap ReadImageFile(string path)
{
//OpenRead
Image result = null;
try
{
using (FileStream fs = File.OpenRead(path))
{
int filelength = 0;
filelength = (int)fs.Length; //获得文件长度
Byte[] image = new Byte[filelength]; //建立一个字节数组
fs.Read(image, 0, filelength); //按字节流读取
result = Image.FromStream(fs);
return new Bitmap(result);
}
}
catch (Exception)
{ }
return null;
}
public static string GetMimeType(string filename)
{
var mime = string.Empty;
var img = ReadImageFile(filename);
if (img != null)
{
mime = GetMimeType(img);
img.Dispose();
}
return mime;
}
public static string GetMimeType(Image image)
{
var ImageCodec = ImageCodecInfo.GetImageDecoders();
foreach (var item in ImageCodec)
{
if (item.FormatID == image.RawFormat.Guid)
return item.MimeType;
}
return "image/unknown";
}
///
/// 解析二维码
///
///
///
public static string DecodeQRCode(Bitmap bitmap)
{
try
{
if (bitmap == null) return string.Empty;
var file = Util.MapFile(Guid.NewGuid().ToString() + ".jpg", "Cache\\Image");
bitmap.Save(file, System.Drawing.Imaging.ImageFormat.Jpeg);
return DecodeQRCode(file);
}
catch (Exception)
{ }
return string.Empty;
}
#endregion
#region AppConfig
// 选择文件:
public static void AppConfig_AddItem(string keyName, string keyValue)
{
//添加配置文件的项,键为keyName,值为keyValue
Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
config.AppSettings.Settings.Add(keyName, keyValue);
config.Save(ConfigurationSaveMode.Modified);
ConfigurationManager.RefreshSection("appSettings");
}
public static bool AppConfig_ExistItem(string keyName)
{
//判断配置文件中是否存在键为keyName的项
foreach (string key in ConfigurationManager.AppSettings)
{
if (key == keyName)
{
//存在
return true;
}
}
return false;
}
public static string AppConfig_GetValue(string keyName)
{
//返回配置文件中键为keyName的项的值
return ConfigurationManager.AppSettings[keyName];
}
public static void AppConfig_RemoveItem(string keyName)
{
//删除配置文件键为keyName的项
Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
config.AppSettings.Settings.Remove(keyName);
config.Save(ConfigurationSaveMode.Modified);
ConfigurationManager.RefreshSection("appSettings");
}
public static bool AppConfig_ModifyItem(string keyName, string newKeyValue)
{
//修改配置文件中键为keyName的项的值
try
{
Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
config.AppSettings.Settings[keyName].Value = newKeyValue;
config.AppSettings.SectionInformation.ForceSave = true;
config.Save(ConfigurationSaveMode.Modified);
ConfigurationManager.RefreshSection("appSettings");
return true;
}
catch (Exception ex)
{
return false;
}
}
#endregion
///
/// 生成指定位数的随机数
///
///
///
public static string GetRandomString(int iLength)
{
try
{
string buffer = "0123456789";// 随机字符中也可以为汉字(任何)
StringBuilder sb = new StringBuilder();
Random r = new Random();
int range = buffer.Length;
for (int i = 0; i < iLength; i++)
{
sb.Append(buffer.Substring(r.Next(range), 1));
}
return sb.ToString();
}
catch (Exception)
{ }
return string.Empty;
}
///
/// 添加水印
///
/// 原图片地址
/// 水印图片地址
/// resMsg[0] 成功,失败
public static byte[] AddWaterMark(byte[] data, string text)
{
try
{
var image = BytesToBitmap(data);
Bitmap bitmap = new Bitmap(image, image.Width, image.Height);
Graphics g = Graphics.FromImage(bitmap);
float fontSize = 12.0f; //字体大小
float textWidth = text.Length * fontSize; //文本的长度
//下面定义一个矩形区域,以后在这个矩形里画上白底黑字
float rectX = 0;
float rectY = 0;
float rectWidth = text.Length * (fontSize + 8);
float rectHeight = fontSize + 8;
//声明矩形域
RectangleF textArea = new RectangleF(rectX, rectY, rectWidth, rectHeight);
Font font = new Font("宋体", fontSize); //定义字体
Brush whiteBrush = new SolidBrush(Color.White); //白笔刷,画文字用
Brush blackBrush = new SolidBrush(Color.Black); //黑笔刷,画背景用
g.FillRectangle(blackBrush, rectX, rectY, rectWidth, rectHeight);
g.DrawString(text, font, whiteBrush, textArea);
MemoryStream ms = new MemoryStream();
//保存为Jpg类型
bitmap.Save(ms, ImageFormat.Jpeg);
Image h_hovercImg = Image.FromStream(ms);
g.Dispose();
bitmap.Dispose();
var temp_data = new byte[ms.Length];
ms.Write(temp_data, 0, temp_data.Length);
ms.Close();
return temp_data;
}
catch (Exception)
{
}
return data;
}
///
/// 给图片添加文字水印
///
/// 图片
/// 文字
/// 文本位置中心点坐标
/// 字体
/// 字体颜色
/// 旋转角度(顺时针)
///
public static Image AddText2Image(Image img, string text, Point p, Font font, Color fontColor, int angle)
{
try
{
using (var g = Graphics.FromImage(img))
using (var brush = new SolidBrush(fontColor))
{
g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.High;
g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;
var sizeF = g.MeasureString(text, font);
g.ResetTransform();
g.TranslateTransform(p.X, p.Y);
g.RotateTransform(angle);
g.DrawString(text, font, brush, new PointF(-sizeF.Width / 2, -sizeF.Height / 2));
}
return img;
}
catch (Exception)
{
}
return null;
}
public static byte[] imageToByteArray(System.Drawing.Image imageIn)
{
MemoryStream ms = new MemoryStream();
imageIn.Save(ms, System.Drawing.Imaging.ImageFormat.Jpeg);
return ms.ToArray();
}
public static Image byteArrayToImage(byte[] byteArrayIn)
{
MemoryStream ms = new MemoryStream(byteArrayIn);
Image returnImage = Image.FromStream(ms);
return returnImage;
}
public static void SendEmail(string host, int port, string username, string userpass, bool ssl, string tousername, string title, string content, bool begin = false, string file = "")
{
if (string.IsNullOrWhiteSpace(username)) throw new Exception("请填写邮箱地址");
System.Net.Mail.SmtpClient client = new System.Net.Mail.SmtpClient();
client.Host = host;//邮件服务器
client.Port = port;//smtp主机上的端口号,默认是25.
client.DeliveryMethod = System.Net.Mail.SmtpDeliveryMethod.Network;//邮件发送方式:通过网络发送到SMTP服务器
client.Credentials = new System.Net.NetworkCredential(username, userpass);//凭证,发件人登录邮箱的用户名和密码
client.Timeout = 5000;
//电子邮件信息类
System.Net.Mail.MailAddress fromAddress = new System.Net.Mail.MailAddress(username, username);//发件人Email,在邮箱是这样显示的,[发件人:小明;]
System.Net.Mail.MailAddress toAddress = new System.Net.Mail.MailAddress(tousername, username);//收件人Email,在邮箱是这样显示的, [收件人:小红<43327681@163.com>;]
System.Net.Mail.MailMessage mailMessage = new System.Net.Mail.MailMessage(fromAddress, toAddress);//创建一个电子邮件类
mailMessage.Subject = title;
// string filePath = Server.MapPath("/index.html");//邮件的内容可以是一个html文本.
//System.IO.StreamReader read = new System.IO.StreamReader(filePath, System.Text.Encoding.GetEncoding("GB2312"));
//string mailBody = read.ReadToEnd();
//read.Close();
mailMessage.Body = content;//可为html格式文本
//mailMessage.Body = "邮件的内容";//可为html格式文本
mailMessage.SubjectEncoding = System.Text.Encoding.UTF8;//邮件主题编码
mailMessage.BodyEncoding = System.Text.Encoding.UTF8;//邮件内容编码
mailMessage.IsBodyHtml = true;//邮件内容是否为html格式
mailMessage.Priority = System.Net.Mail.MailPriority.Normal;//邮件的优先级,有三个值:高(在邮件主题前有一个红色感叹号,表示紧急),低(在邮件主题前有一个蓝色向下箭头,表示缓慢),正常(无显示).
#region
//添加附件
if (!string.IsNullOrWhiteSpace(file))
{
//string extName = Path.GetExtension(file).ToLower();
////这里仅举例说明如何判断附件类型
//if (extName == ".rar" || extName == ".zip")
// attachment = new Attachment(file, MediaTypeNames.Application.Zip);
//else
// attachment = new Attachment(file, MediaTypeNames.Application.Octet);
//ContentDisposition cd = attachment.ContentDisposition;
//cd.CreationDate = File.GetCreationTime(file);
//cd.ModificationDate = File.GetLastWriteTime(file);
//cd.ReadDate = File.GetLastAccessTime(file);
//mailMessage.Attachments.Add(attachment);
//SUpFile = Server.MapPath("~/发邮件/Upfile/" + SUpFile);//获得附件在本地地址
//将文件进行转换成Attachments
Attachment data = new Attachment(file, MediaTypeNames.Application.Octet);
// Add time stamp information for the file.
ContentDisposition disposition = data.ContentDisposition;
disposition.CreationDate = System.IO.File.GetCreationTime(file);
disposition.ModificationDate = System.IO.File.GetLastWriteTime(file);
disposition.ReadDate = System.IO.File.GetLastAccessTime(file);
mailMessage.Attachments.Add(data);
System.Net.Mime.ContentType ctype = new System.Net.Mime.ContentType();
}
#endregion
client.EnableSsl = ssl;
if (begin)
client.SendAsync(mailMessage, "ojb");
else
client.Send(mailMessage);//发送邮件
}
const string Seq = "s9LFkgy5RovixI1aOf8UhdY3r4DMplQZJXPqebE0WSjBn7wVzmN2Gc6THCAKut";
///
/// 10进制转换为62进制
///
///
///
public static string InvitationCode(long id)
{
if (id < 62)
{
return Seq[(int)id].ToString();
}
int y = (int)(id % 62);
long x = (long)(id / 62);
return InvitationCode(x) + Seq[y];
}
public static long InvitationCode(string Num)
{
long v = 0;
int Len = Num.Length;
for (int i = Len - 1; i >= 0; i--)
{
int t = Seq.IndexOf(Num[i]);
double s = (Len - i) - 1;
long m = (long)(Math.Pow(62, s) * t);
v += m;
}
return v;
}
public static string HexToStr(byte[] bytes)
{
string returnStr = "";
if (bytes != null)
{
for (int i = 0; i < bytes.Length; i++)
{
returnStr += bytes[i].ToString("X2");
}
}
return returnStr;
}
public static byte[] StrToHex(string hexString)
{
hexString = hexString.Replace(" ", "");
if ((hexString.Length % 2) != 0)
{
hexString = hexString + " ";
}
byte[] buffer = new byte[hexString.Length / 2];
for (int i = 0; i < buffer.Length; i++)
{
buffer[i] = Convert.ToByte(hexString.Substring(i * 2, 2), 0x10);
}
return buffer;
}
public static string GetMd5_32byte(string str)
{
string pwd = string.Empty;
//实例化一个md5对像
MD5 md5 = MD5.Create();
// 加密后是一个字节类型的数组,这里要注意编码UTF8/Unicode等的选择
byte[] s = md5.ComputeHash(Encoding.UTF8.GetBytes(str));
// 通过使用循环,将字节类型的数组转换为字符串,此字符串是常规字符格式化所得
for (int i = 0; i < s.Length; i++)
{
// 将得到的字符串使用十六进制类型格式。格式后的字符是小写的字母,如果使用大写(X)则格式后的字符是大写字符
pwd = pwd + s[i].ToString("X");
}
return pwd;
}
public static string GetFileMd5Code(string filePath)
{
StringBuilder builder = new StringBuilder();
using (var md5 = new MD5CryptoServiceProvider())
{
File.Copy(filePath, filePath + ".bak");//复制一份,防止占用
using (FileStream fs = new FileStream(filePath + ".bak", FileMode.Open))
{
byte[] bt = md5.ComputeHash(fs);
for (int i = 0; i < bt.Length; i++)
{
builder.Append(bt[i].ToString("x2"));
}
}
File.Delete(filePath + ".bak");//删除复制的文件,这里没处理异常等....
}
return builder.ToString();
}
public static string TimeDiffer(DateTime time)
{
var c = DateTime.Now - time;
return string.Format("{0}天{1}小时{2}分", c.Days, c.Hours, c.Minutes);
}
public static T ConvertEnum(string value)
{
var v = Enum.Parse(typeof(T), value);
return (T)v;
}
public static T ConvertEnum(int value)
{
return (T)Enum.Parse(typeof(T), value.ToString());
}
public static T ConvertEnum(ushort value)
{
return (T)Enum.Parse(typeof(T), value.ToString());
}
///
/// 读取配置文件
///
///
public static T Read(string name = "")
{
var obj = System.Activator.CreateInstance();
ConfigAttribute _attribute = obj.GetType().GetCustomAttributes().FirstOrDefault(f => typeof(ConfigAttribute) == f.GetType()) as ConfigAttribute;
if (_attribute == null) _attribute = new ConfigAttribute();
//配置文件名
string _name = name;
if (string.IsNullOrEmpty(_name))
{
if (string.IsNullOrEmpty(_attribute.Name)) _name = obj.GetType().ToString(); else _name = _attribute.Name;
}
string text = string.Empty;
if (_attribute.IsSaveDB)
{
var session = ApiClient.GetSession();
var _db_item = session.FindDictionaryItem(_name);
if (_db_item != null)
{
text = _db_item.dicvalue;
}
else return obj;
}
else
{
string fileName = MapFile(_name + ".config", "Config");
if (!File.Exists(fileName)) return obj;
text = File.ReadAllText(fileName, Encoding.UTF8);
}
byte[] bytes = HexToByte(text);
if (_attribute.IsEncryption)
{
bytes = TeaEncryption.Decrypt(bytes, _attribute.EncKey);
}
string json = Encoding.UTF8.GetString(bytes);
try
{
return ToDeserialize(json);
}
catch (Exception)
{
try
{
if (_name == "系统.其他设置")
{
json = "{\"Plugins\":[\"MessageSupervises.Class1\",\"PointManage.Class1\",\"TBRebate.Class1\",\"JDRebate.Class1\",\"PDDRebate.Class1\",\"AutoAnswer.Class1\",\"PointConvert.MyPlugin\",\"WPHRebate.Class1\",\"GroupSend2019.MyPlugin\",\"InviteGroup2020.MyPlugin\",\"UserFission.Class1\",\"ProductClient.Class1\",\"DYRebate.Class1\",\"SNRebate.Class1\"]}";
}
return JsonConvert.DeserializeObject(json);
}
catch (Exception)
{ }
}
return default(T);
}
///
/// 将图片转换为字节数组
///
/// 完整的图片路径
///
public static byte[] GetImageByte(string imagePath)
{
FileStream files = new FileStream(imagePath, FileMode.Open);
byte[] imgByte = new byte[files.Length];
files.Read(imgByte, 0, imgByte.Length);
files.Close();
return imgByte;
}
///
/// 将图片Bitmap类型转成字节数组
///
///
///
public static byte[] GetImageByte(System.Drawing.Bitmap bmp)
{
byte[] bytes = null;
try
{
MemoryStream ms = new MemoryStream();
bmp.Save(ms, System.Drawing.Imaging.ImageFormat.Bmp);
bytes = ms.GetBuffer(); //byte[] bytes= ms.ToArray(); 这两句都可以,至于区别么,下面有解释
ms.Close();
}
catch (Exception)
{ }
return bytes;
}
///
/// 获取一个淘口令前后随机修饰符
///
/// 要随机的修饰符
/// 分隔符,默认'|'
/// 返回随机的一个修饰符或传入的str值
public static string FindTKlRandomModifier(string str, char separator = '|')
{
try
{
var modifiers = str.Split(separator);
if (modifiers != null && modifiers.Length != 0)
{
Random random = new Random();
return modifiers[random.Next(0, modifiers.Length)];
}
}
catch (Exception)
{ }
return str;
}
private readonly static object save_config_lock = new object();
///
/// 保存配置文件
///
///
public static void Save(Object obj, string name = "")
{
lock (save_config_lock)
{
try
{
var bytes = Encoding.UTF8.GetBytes(ToSerializer(obj));
var _class = obj.GetType();
var _attribute = _class.GetCustomAttributes().FirstOrDefault() as ConfigAttribute;
if (_attribute == null) _attribute = new ConfigAttribute();
//配置文件名
string _name = name;
if (string.IsNullOrEmpty(_name))
{
if (string.IsNullOrEmpty(_attribute.Name)) _name = obj.GetType().ToString(); else _name = _attribute.Name;
}
var _properties = _class.GetProperties();
foreach (var property in _properties)
{
var attributes = property.GetCustomAttributes();
}
if (_attribute.IsEncryption)
{
bytes = TeaEncryption.Decrypt(bytes, _attribute.EncKey);
}
var hex = ByteToHex(bytes);
if (_attribute.IsSaveDB)
{
var session = ApiClient.GetSession();
var _db_item = session.FindDictionaryItem(_name);
if (_db_item == null) _db_item = new fl_dictionary_item() { dickey = _name };
_db_item.dicvalue = hex;
session.SaveOrUpdate(_db_item);
session.FindDictionaryItem(_name, true);
}
else
{
var fileName = MapFile(_name + ".config", "Config");
File.WriteAllText(fileName, hex, Encoding.UTF8);
}
}
catch (Exception ex)
{
EventClient.OnEvent("", $"【配置文件】保存失败,{ex.Message}");
}
}
}
public static string MapFile(string file, string path = "")
{
return Path.Combine(MapPath(path, true), file);
}
public static string MapPath(string path = "", bool CreateDirectory = true)
{
if (string.IsNullOrWhiteSpace(path))
{
return System.Windows.Forms.Application.StartupPath.ToString() + "\\";
}
path = Path.Combine(System.Windows.Forms.Application.StartupPath.ToString() + "\\", path);
if (!(!CreateDirectory || Directory.Exists(path)))
{
Directory.CreateDirectory(path);
}
return path;
}
public static byte[] BitmapToBytes(Bitmap Bitmap)
{
MemoryStream ms = null;
try
{
ms = new MemoryStream();
Bitmap.Save(ms, Bitmap.RawFormat);
byte[] byteImage = new Byte[ms.Length];
byteImage = ms.ToArray();
return byteImage;
}
catch (ArgumentNullException ex)
{ }
finally
{
ms.Close();
}
return null;
}
public static string GetMD5Hash(byte[] bytedata)
{
try
{
System.Security.Cryptography.MD5 md5 = new System.Security.Cryptography.MD5CryptoServiceProvider();
byte[] retVal = md5.ComputeHash(bytedata);
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("GetMD5Hash() fail,error:" + ex.Message);
}
}
public static Bitmap BytesToBitmap(byte[] Bytes)
{
MemoryStream stream = null;
try
{
stream = new MemoryStream(Bytes);
return new Bitmap(stream);
}
catch (ArgumentNullException ex)
{
throw ex;
}
catch (ArgumentException ex)
{
throw ex;
}
finally
{
stream.Close();
}
}
///
/// 图像灰度化
///
public static Bitmap ToGrey(System.Drawing.Image image)
{
Bitmap img = new Bitmap(image);
for (int i = 0; i < img.Width; i++)
{
for (int j = 0; j < img.Height; j++)
{
Color pixelColor = img.GetPixel(i, j);
int grey = (int)(0.299 * pixelColor.R + 0.587 * pixelColor.G + 0.114 * pixelColor.B);
Color newColor = Color.FromArgb(grey, grey, grey, grey);
img.SetPixel(i, j, newColor);
}
}
return img;
}
public static T ToDeserialize(string content)
{
JavaScriptSerializer serializer = new JavaScriptSerializer();
serializer.MaxJsonLength = Int32.MaxValue;
return serializer.Deserialize(content);
}
public static string ToSerializer(Object entity)
{
JavaScriptSerializer serializer = new JavaScriptSerializer();
serializer.MaxJsonLength = Int32.MaxValue;
return serializer.Serialize(entity);
}
private static string ByteToHex(byte[] bytes)
{
return BitConverter.ToString(bytes, 0).Replace("-", string.Empty).ToLower();
}
private static byte[] HexToByte(string hex)
{
var inputByteArray = new byte[hex.Length / 2];
for (var x = 0; x < inputByteArray.Length; x++)
{
var i = Convert.ToInt32(hex.Substring(x * 2, 2), 16);
inputByteArray[x] = (byte)i;
}
return inputByteArray;
}
///
/// 下载文件
///
/// 下载文件地址
/// 下载后的存放地址
/// 用于显示的进度条
public void DownloadFile(string url, string filename, System.Windows.Forms.ProgressBar prog = null)
{
float percent = 0;
try
{
System.Net.HttpWebRequest Myrq = (System.Net.HttpWebRequest)System.Net.HttpWebRequest.Create(url);
System.Net.HttpWebResponse myrp = (System.Net.HttpWebResponse)Myrq.GetResponse();
long totalBytes = myrp.ContentLength;
if (prog != null) prog.Maximum = (int)totalBytes;
System.IO.Stream st = myrp.GetResponseStream();
System.IO.Stream so = new System.IO.FileStream(filename, System.IO.FileMode.Create);
long totalDownloadedByte = 0;
byte[] by = new byte[1024];
int osize = st.Read(by, 0, (int)by.Length);
while (osize > 0)
{
totalDownloadedByte = osize + totalDownloadedByte;
System.Windows.Forms.Application.DoEvents();
so.Write(by, 0, osize);
if (prog != null) prog.Value = (int)totalDownloadedByte;
osize = st.Read(by, 0, (int)by.Length);
percent = (float)totalDownloadedByte / (float)totalBytes * 100;
System.Windows.Forms.Application.DoEvents(); //必须加注这句代码,否则label1将因为循环执行太快而来不及显示信息
}
so.Close();
st.Close();
}
catch (System.Exception)
{
throw;
}
}
///
/// 下载HTML
///
/// 地址
/// Post参数
///
public string DownloadHtml(string url, string data = "")
{
HttpHelper http = new HttpHelper();
HttpItem item = new HttpItem()
{
URL = url,//URL 必需项
Method = string.IsNullOrEmpty(data) ? "GET" : "POST",//URL 可选项 默认为Get
Timeout = 5000,//连接超时时间 可选项默认为100000
ReadWriteTimeout = 5000,//写入Post数据超时时间 可选项默认为30000
IsToLower = false,//得到的HTML代码是否转成小写 可选项默认转小写
Cookie = "",//字符串Cookie 可选项
UserAgent = "Mozilla/5.0 (Windows NT 6.1; WOW64; rv:18.0) Gecko/20100101 Firefox/18.0",//用户的浏览器类型,版本,操作系统 可选项有默认值
Accept = "text/html, application/xhtml+xml, */*",// 可选项有默认值
ContentType = "application/x-www-form-urlencoded",//返回类型 可选项有默认值
Referer = "",//来源URL 可选项
Allowautoredirect = true,//是否根据301跳转 可选项
Postdata = data
};
HttpResult result = http.GetHtml(item);
return result.Html;
}
///
/// 读取数据
///
/// 文件路径
public byte[] ReadFile(string path)
{
using (FileStream stream = new FileStream(path, FileMode.Open))
{
using (MemoryStream memStream = new MemoryStream())
{
int res;
byte[] b = new byte[stream.Length];
while ((res = stream.Read(b, 0, b.Length)) > 0)
{
memStream.Write(b, 0, b.Length);
}
return b;
}
}
}
#region Cookies 操作
///
/// 设置IE
///
/// hInternet
/// dwOption
/// lpBuffer
/// lpdwBufferLength
/// 处理结果
[DllImport("wininet.dll", SetLastError = true)]
public static extern bool InternetSetOption(IntPtr hInternet, int dwOption, IntPtr lpBuffer, int lpdwBufferLength);
[DllImport("shell32.dll")]
static extern IntPtr ShellExecute(IntPtr hwnd, string lpOperation, string lpFile, string lpParameters, string lpDirectory, int nShowCmd);
public static void ClearCookies()
{
try
{
InternetSetOption(IntPtr.Zero, 42, IntPtr.Zero, 0);
//SuppressWininetBehavior();
ShellExecute(IntPtr.Zero, "open", "rundll32.exe", " InetCpl.cpl,ClearMyTracksByProcess 255", "", 0);
CleanAll();
}
catch (Exception ex)
{
//Console.WriteLine(ex.Message);
}
}
public static void CleanAll()
{
CleanCookie();
CleanHistory();
CleanTempFiles();
}
[DllImport("wininet.dll", CharSet = System.Runtime.InteropServices.CharSet.Auto, SetLastError = true)]
private static extern bool InternetSetOption(int hInternet, int dwOption, IntPtr lpBuffer, int dwBufferLength);
public static unsafe void SuppressWininetBehavior()
{
try
{
int option = (int)3/* INTERNET_SUPPRESS_COOKIE_PERSIST*/;
int* optionPtr = &option;
bool success = InternetSetOption(0, 81/*INTERNET_OPTION_SUPPRESS_BEHAVIOR*/, new IntPtr(optionPtr), sizeof(int));
}
catch (Exception ex) { }
}
///
/// 拷贝oldlab的文件到newlab下面
///
/// lab文件所在目录(@"~\labs\oldlab")
/// 保存的目标目录(@"~\labs\newlab")
/// 返回:true-拷贝成功;false:拷贝失败
public static bool CopyOldLabFilesToNewLab(string sourcePath, string savePath)
{
if (!Directory.Exists(savePath))
{
Directory.CreateDirectory(savePath);
}
#region //拷贝labs文件夹到savePath下
try
{
string[] labDirs = Directory.GetDirectories(sourcePath);//目录
string[] labFiles = Directory.GetFiles(sourcePath);//文件
if (labFiles.Length > 0)
{
for (int i = 0; i < labFiles.Length; i++)
{
if (Path.GetExtension(labFiles[i]) != ".lab")//排除.lab文件
{
File.Copy(sourcePath + "\\" + Path.GetFileName(labFiles[i]), savePath + "\\" + Path.GetFileName(labFiles[i]), true);
}
}
}
if (labDirs.Length > 0)
{
for (int j = 0; j < labDirs.Length; j++)
{
Directory.GetDirectories(sourcePath + "\\" + Path.GetFileName(labDirs[j]));
//递归调用
CopyOldLabFilesToNewLab(sourcePath + "\\" + Path.GetFileName(labDirs[j]), savePath + "\\" + Path.GetFileName(labDirs[j]));
}
}
}
catch (Exception)
{
return false;
}
#endregion
return true;
}
///
/// 删除历史记录 Win7+ 需要管理员权限
///
public static void CleanHistory()
{
string[] theFiles = System.IO.Directory.GetFiles(Environment.GetFolderPath(Environment.SpecialFolder.History), "*", System.IO.SearchOption.AllDirectories);
foreach (string s in theFiles)
FileDelete(s);
RunCmd("RunDll32.exe InetCpl.cpl,ClearMyTracksByProcess 1");
}
///
/// 调用CMD执行命令
///
///
public static void RunCmd(string cmd)
{
System.Diagnostics.Process p = new System.Diagnostics.Process();
p.StartInfo.FileName = "cmd.exe";
// 关闭Shell的使用
p.StartInfo.UseShellExecute = false;
// 重定向标准输入
p.StartInfo.RedirectStandardInput = true;
// 重定向标准输出
p.StartInfo.RedirectStandardOutput = true;
//重定向错误输出
p.StartInfo.RedirectStandardError = true;
p.StartInfo.CreateNoWindow = true;
p.Start();
p.StandardInput.WriteLine(cmd);
p.StandardInput.WriteLine("exit");
}
///
/// 删除一个文件,System.IO.File.Delete()函数不可以删除只读文件,这个函数可以强行把只读文件删除。
///
/// 文件路径
/// 成功为true
public static bool FileDelete(string path)
{
//first set the File\'s ReadOnly to 0
//if EXP, restore its Attributes
System.IO.FileInfo file = new System.IO.FileInfo(path);
System.IO.FileAttributes att = 0;
bool attModified = false;
try
{
//### ATT_GETnSET
att = file.Attributes;
file.Attributes &= (~System.IO.FileAttributes.ReadOnly);
attModified = true;
file.Delete();
}
catch
{
if (attModified)
file.Attributes = att;
return false;
}
return true;
}
///
/// 删除文件夹
///
/// 文件夹路径
public static void FolderClear(string path)
{
System.IO.DirectoryInfo diPath = new System.IO.DirectoryInfo(path);
foreach (System.IO.FileInfo fiCurrFile in diPath.GetFiles())
{
FileDelete(fiCurrFile.FullName);
}
foreach (System.IO.DirectoryInfo diSubFolder in diPath.GetDirectories())
{
FolderClear(diSubFolder.FullName); // Call recursively for all subfolders
}
}
///
/// 删除临时文件 Win7+ 需要管理员权限
///
public static void CleanTempFiles()
{
FolderClear(Environment.GetFolderPath(Environment.SpecialFolder.InternetCache));
RunCmd("RunDll32.exe InetCpl.cpl,ClearMyTracksByProcess 8");
}
///
/// 删除Cookie文件 Win7+ 需要管理员权限
///
public static void CleanCookie()
{
string[] theFiles = System.IO.Directory.GetFiles(Environment.GetFolderPath(Environment.SpecialFolder.Cookies), "*", System.IO.SearchOption.AllDirectories);
foreach (string s in theFiles)
FileDelete(s);
RunCmd("RunDll32.exe InetCpl.cpl,ClearMyTracksByProcess 2");
}
#endregion
///
/// 是否为XML
///
///
///
public static bool IsXML(string mess)
{
return mess.Contains("硬盘文件路径
///
public static byte[] ReadFileToByte(string fileName)
{
FileStream pFileStream = null;
byte[] pReadByte = new byte[0];
try
{
pFileStream = new FileStream(fileName, FileMode.Open, FileAccess.Read);
BinaryReader r = new BinaryReader(pFileStream);
r.BaseStream.Seek(0, SeekOrigin.Begin); //将文件指针设置到文件开
pReadByte = r.ReadBytes((int)r.BaseStream.Length);
return pReadByte;
}
catch
{
return pReadByte;
}
finally
{
if (pFileStream != null)
pFileStream.Close();
}
}
///
/// 写byte[]到fileName
///
/// byte[]
/// 保存至硬盘路径
///
public static bool WriteByteToFile(byte[] pReadByte, string fileName)
{
FileStream pFileStream = null;
try
{
pFileStream = new FileStream(fileName, FileMode.OpenOrCreate);
pFileStream.Write(pReadByte, 0, pReadByte.Length);
}
catch
{
return false;
}
finally
{
if (pFileStream != null)
pFileStream.Close();
}
return true;
}
public static string RemoveEmoji(string text)
{
if (string.IsNullOrEmpty(text)) return string.Empty;
if (!string.IsNullOrEmpty(System.Configuration.ConfigurationManager.AppSettings["RemoveWechatEmoji"]) && System.Configuration.ConfigurationManager.AppSettings["RemoveWechatEmoji"].ToUpper() == "FALSE")
{
return text;
}
text = Regex.Replace(text, @"\%uD.{3}", "");
text = Regex.Replace(text, "[👃☺️☹️☠️✊✌️☝✋✍️♀️♂️]", "");
foreach (var a in text)
{
byte[] bts = Encoding.UTF32.GetBytes(a.ToString());
if (bts[0].ToString() == "253" && bts[1].ToString() == "255")
{
text = text.Replace(a.ToString(), "");
}
}
return text;
}
public static bool ShowTgwz()
{
var session = ApiClient.GetSession();
var count = session.Find("select * from fl_adzone_group").Count();
if (count != 0) return true;
var ShowTgwz = AppConfig_GetValue("ShowTgwz");
return (ShowTgwz != null && ShowTgwz == "1");
}
///
/// 文件转换成Base64字符串
///
/// 文件绝对路径
///
public static String FileToBase64(string fileName)
{
string strRet = "";
try
{
FileStream fs = new FileStream(fileName, FileMode.Open);
byte[] bt = new byte[fs.Length];
fs.Read(bt, 0, bt.Length);
strRet = Convert.ToBase64String(bt);
fs.Close();
}
catch (Exception ex)
{
strRet = null;
}
return strRet;
}
///
/// Base64字符串转换成文件
///
/// base64字符串
/// 保存文件的绝对路径
///
public static bool Base64ToFileAndSave(string strInput, string fileName)
{
bool bTrue = false;
try
{
byte[] buffer = Convert.FromBase64String(strInput);
FileStream fs = new FileStream(fileName, FileMode.OpenOrCreate);
fs.Write(buffer, 0, buffer.Length);
fs.Close();
bTrue = true;
}
catch (Exception ex)
{ }
return bTrue;
}
///
/// 将图片控制在宽度为指定得像素
///
///
///
///
public static Bitmap PercentImage(Image srcImage, int size = 200)
{
int newW = srcImage.Width < size ? srcImage.Width : size;
int newH = int.Parse(Math.Round(srcImage.Height * (double)newW / srcImage.Width).ToString());
try
{
Bitmap b = new Bitmap(newW, newH);
Graphics g = Graphics.FromImage(b);
g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.Default;
g.DrawImage(srcImage, new Rectangle(0, 0, newW, newH), new Rectangle(0, 0, srcImage.Width, srcImage.Height), GraphicsUnit.Pixel);
g.Dispose();
return b;
}
catch (Exception)
{
return null;
}
}
///
/// 将图片按百分比压缩,
///
///
///
/// flag取值1到100,越小压缩比越大
///
public static bool YaSuo(Image iSource, string outPath, int flag = 80)
{
ImageFormat tFormat = iSource.RawFormat;
EncoderParameters ep = new EncoderParameters();
long[] qy = new long[1];
qy[0] = flag;
EncoderParameter eParam = new EncoderParameter(System.Drawing.Imaging.Encoder.Quality, qy);
ep.Param[0] = eParam;
try
{
ImageCodecInfo[] arrayICI = ImageCodecInfo.GetImageDecoders();
ImageCodecInfo jpegICIinfo = null;
for (int x = 0; x < arrayICI.Length; x++)
{
if (arrayICI[x].FormatDescription.Equals("JPEG"))
{
jpegICIinfo = arrayICI[x];
break;
}
}
if (jpegICIinfo != null)
iSource.Save(outPath, jpegICIinfo, ep);
else
iSource.Save(outPath, tFormat);
return true;
}
catch
{
return false;
}
iSource.Dispose();
}
///
/// 日期转换成时间戳Timestamp
///
///
///
public static long GetTimeSpan(DateTime time)
{
DateTime dtStart = TimeZone.CurrentTimeZone.ToLocalTime(new DateTime(1970, 1, 1));
return (long)(time - dtStart).TotalMilliseconds;
}
///
/// 日期转换成时间戳Timestamp
///
///
///
public static long GetTimeSpan(DateTime time, bool Milliseconds = false)
{
DateTime dtStart = TimeZone.CurrentTimeZone.ToLocalTime(new DateTime(1970, 1, 1));
if (!Milliseconds)
return (long)(time - dtStart).TotalSeconds;
else
return (long)(time - dtStart).TotalMilliseconds;
}
///
/// 时间戳转时间
///
///
///
public static DateTime GetDateTime(long timeSpan)
{
DateTime dtStart = TimeZone.CurrentTimeZone.ToLocalTime(new DateTime(1970, 1, 1));
if (timeSpan.ToString().Length == 13)
return dtStart.AddMilliseconds(timeSpan);
else
return dtStart.AddSeconds(timeSpan);
}
///
/// 获取UUID
///
///
public static string GetUUID()
{
return System.Guid.NewGuid().ToString("N");
}
#region 加密
//默认密钥向量
private static byte[] Keys = { 0x42, 0x34, 0x56, 0x3C, 0x90, 0xAB, 0xAD, 0xEE };
////
/// DES加密字符串
///
/// 待加密的字符串
/// 加密密钥,要求为8位
/// 加密成功返回加密后的字符串,失败返回源串
public static string EncryptDES(string encryptString, string encryptKey = "2#~1*oW0")
{
try
{
byte[] rgbKey = Encoding.UTF8.GetBytes(encryptKey.Substring(0, 8));
byte[] rgbIV = Keys;
byte[] inputByteArray = Encoding.UTF8.GetBytes(encryptString);
DESCryptoServiceProvider dCSP = new DESCryptoServiceProvider();
MemoryStream mStream = new MemoryStream();
CryptoStream cStream = new CryptoStream(mStream, dCSP.CreateEncryptor(rgbKey, rgbIV), CryptoStreamMode.Write);
cStream.Write(inputByteArray, 0, inputByteArray.Length);
cStream.FlushFinalBlock();
return Convert.ToBase64String(mStream.ToArray());
}
catch
{
return encryptString;
}
}
////
/// DES解密字符串
///
/// 待解密的字符串
/// 解密密钥,要求为8位,和加密密钥相同
/// 解密成功返回解密后的字符串,失败返源串
public static string DecryptDES(string decryptString, string decryptKey = "2#~1*oW0")
{
try
{
byte[] rgbKey = Encoding.UTF8.GetBytes(decryptKey);
byte[] rgbIV = Keys;
byte[] inputByteArray = Convert.FromBase64String(decryptString);
DESCryptoServiceProvider DCSP = new DESCryptoServiceProvider();
MemoryStream mStream = new MemoryStream();
CryptoStream cStream = new CryptoStream(mStream, DCSP.CreateDecryptor(rgbKey, rgbIV), CryptoStreamMode.Write);
cStream.Write(inputByteArray, 0, inputByteArray.Length);
cStream.FlushFinalBlock();
return Encoding.UTF8.GetString(mStream.ToArray());
}
catch
{
return decryptString;
}
}
#endregion
}
public class EnumHelper
{
///
/// 将枚举转为集合
///
///
///
public static List EnumToList()
{
List list = new List();
foreach (var e in Enum.GetValues(typeof(T)))
{
EnumEntity m = new EnumEntity();
object[] objArr = e.GetType().GetField(e.ToString()).GetCustomAttributes(typeof(DescriptionAttribute), true);
if (objArr != null && objArr.Length > 0)
{
DescriptionAttribute da = objArr[0] as DescriptionAttribute;
m.Desction = da.Description;
}
m.EnumValue = Convert.ToInt32(e);
m.EnumName = e.ToString();
list.Add(m);
}
return list;
}
///
/// 获取枚举描述
///
///
///
///
public static string GetEnumDesction(string EnumName)
{
foreach (var e in Enum.GetValues(typeof(T)))
{
if (e.ToString() != EnumName)
continue;
EnumEntity m = new EnumEntity();
object[] objArr = e.GetType().GetField(e.ToString()).GetCustomAttributes(typeof(DescriptionAttribute), true);
if (objArr != null && objArr.Length > 0)
{
DescriptionAttribute da = objArr[0] as DescriptionAttribute;
return da.Description;
}
}
return "";
}
}
///
/// 枚举实体
///
public class EnumEntity
{
///
/// 枚举的描述
///
public string Desction { set; get; }
///
/// 枚举名称
///
public string EnumName { set; get; }
///
/// 枚举对象的值
///
public int EnumValue { set; get; }
}
}