2130 lines
81 KiB
C#
2130 lines
81 KiB
C#
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
|
||
{
|
||
|
||
/// <summary>
|
||
/// 将数据转成对象
|
||
/// </summary>
|
||
/// <typeparam name="T"></typeparam>
|
||
/// <param name="data"></param>
|
||
/// <returns></returns>
|
||
public static T ToObj<T>(JToken data)
|
||
{
|
||
try
|
||
{
|
||
if (data == null)
|
||
return default(T);
|
||
//return JsonConvert.DeserializeObject<T>(JsonConvert.SerializeObject(data));
|
||
return data.ToObject<T>();
|
||
}
|
||
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();
|
||
/// <summary>
|
||
/// 检测微信域名是否正常
|
||
/// </summary>
|
||
/// <param name="url"></param>
|
||
/// <param name="noticeName"></param>
|
||
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)
|
||
{ }
|
||
}
|
||
}
|
||
|
||
/// <summary>
|
||
/// 获取小程序xml文本
|
||
/// </summary>
|
||
/// <param name="data"></param>
|
||
/// <param name="chatType"></param>
|
||
/// <returns></returns>
|
||
public static string GetMiNiAppXml(object data, ChatType chatType)
|
||
{
|
||
var xml = string.Empty;
|
||
try
|
||
{
|
||
if (data != null)
|
||
{
|
||
if (data is Dictionary<string, object>)
|
||
{
|
||
var dic = data as Dictionary<string, object>;
|
||
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 = $@"<appmsg appid='' sdkver='0'>
|
||
<title><![CDATA[兑换成功,请注意查收]]></title>
|
||
<des><![CDATA[]]></des>
|
||
<username />
|
||
<action>view</action>
|
||
<type>33</type>
|
||
<showtype>0</showtype>
|
||
<content />
|
||
<url />
|
||
<lowurl />
|
||
<forwardflag>0</forwardflag>
|
||
<dataurl />
|
||
<lowdataurl />
|
||
<contentattr>0</contentattr>
|
||
<streamvideo>
|
||
<streamvideourl />
|
||
<streamvideototaltime>0</streamvideototaltime>
|
||
<streamvideotitle />
|
||
<streamvideowording />
|
||
<streamvideoweburl />
|
||
<streamvideothumburl />
|
||
<streamvideoaduxinfo />
|
||
<streamvideopublishid />
|
||
</streamvideo>
|
||
<canvasPageItem>
|
||
<canvasPageXml><![CDATA[]]></canvasPageXml>
|
||
</canvasPageItem>
|
||
<appattach>
|
||
<attachid />
|
||
<cdnthumburl>308182020100047b30790201000204241402cf02032f53a102046aed7b7602046140580404546175706170706d73675f313964303238376430373335333963355f313633313630363738383235345f3737303538355f30663530663632362d316535632d343235352d613136352d6530316361333464353736300204011800030201000400</cdnthumburl>
|
||
<cdnthumbmd5>308ac8283026da65a796d699318d218c</cdnthumbmd5>
|
||
<cdnthumblength>12820</cdnthumblength>
|
||
<cdnthumbheight>576</cdnthumbheight>
|
||
<cdnthumbwidth>720</cdnthumbwidth>
|
||
<cdnthumbaeskey>5951804402693f81eb27633f194a6a68</cdnthumbaeskey>
|
||
<aeskey>5951804402693f81eb27633f194a6a68</aeskey>
|
||
<encryver>1</encryver>
|
||
<fileext />
|
||
<islargefilemsg>0</islargefilemsg>
|
||
</appattach>
|
||
<extinfo />
|
||
<androidsource>3</androidsource>
|
||
<thumburl>https://fd-1300509451.cos.ap-chengdu.myqcloud.com/fm1.jpeg</thumburl>
|
||
<mediatagname />
|
||
<messageaction><![CDATA[]]></messageaction>
|
||
<messageext><![CDATA[]]></messageext>
|
||
<emoticongift>
|
||
<packageflag>0</packageflag>
|
||
<packageid />
|
||
</emoticongift>
|
||
<emoticonshared>
|
||
<packageflag>0</packageflag>
|
||
<packageid />
|
||
</emoticonshared>
|
||
<designershared>
|
||
<designeruin>0</designeruin>
|
||
<designername>null</designername>
|
||
<designerrediretcturl>null</designerrediretcturl>
|
||
</designershared>
|
||
<emotionpageshared>
|
||
<tid>0</tid>
|
||
<title>null</title>
|
||
<desc>null</desc>
|
||
<iconUrl>null</iconUrl>
|
||
<secondUrl />
|
||
<pageType>0</pageType>
|
||
</emotionpageshared>
|
||
<webviewshared>
|
||
<shareUrlOriginal />
|
||
<shareUrlOpen />
|
||
<jsAppId />
|
||
<publisherId />
|
||
</webviewshared>
|
||
<template_id />
|
||
<md5>308ac8283026da65a796d699318d218c</md5>
|
||
<weappinfo>
|
||
<pagepath><![CDATA[{target}]]></pagepath>
|
||
<username><![CDATA[{appname}@app]]></username>
|
||
<appid><![CDATA[{appid}]]></appid>
|
||
<type>2</type>
|
||
<appservicetype>0</appservicetype>
|
||
<secflagforsinglepagemode>0</secflagforsinglepagemode>
|
||
<videopageinfo>
|
||
<thumbwidth>720</thumbwidth>
|
||
<thumbheight>576</thumbheight>
|
||
<fromopensdk>0</fromopensdk>
|
||
</videopageinfo>
|
||
</weappinfo>
|
||
<statextstr />
|
||
<musicShareItem>
|
||
<musicDuration>0</musicDuration>
|
||
</musicShareItem>
|
||
<finderLiveProductShare>
|
||
<finderLiveID><![CDATA[]]></finderLiveID>
|
||
<finderUsername><![CDATA[]]></finderUsername>
|
||
<finderObjectID><![CDATA[]]></finderObjectID>
|
||
<finderNonceID><![CDATA[]]></finderNonceID>
|
||
<liveStatus><![CDATA[]]></liveStatus>
|
||
<appId><![CDATA[]]></appId>
|
||
<pagePath><![CDATA[]]></pagePath>
|
||
<productId><![CDATA[]]></productId>
|
||
<coverUrl><![CDATA[]]></coverUrl>
|
||
<productTitle><![CDATA[]]></productTitle>
|
||
<marketPrice><![CDATA[0]]></marketPrice>
|
||
<sellingPrice><![CDATA[0]]></sellingPrice>
|
||
<platformHeadImg><![CDATA[]]></platformHeadImg>
|
||
<platformName><![CDATA[]]></platformName>
|
||
<shopWindowId><![CDATA[]]></shopWindowId>
|
||
</finderLiveProductShare>
|
||
<findernamecard>
|
||
<username />
|
||
<avatar><![CDATA[]]></avatar>
|
||
<nickname />
|
||
<auth_job />
|
||
<auth_icon>0</auth_icon>
|
||
<auth_icon_url />
|
||
</findernamecard>
|
||
<finderGuarantee>
|
||
<scene><![CDATA[0]]></scene>
|
||
</finderGuarantee>
|
||
<directshare>0</directshare>
|
||
<gamecenter>
|
||
<namecard>
|
||
<iconUrl />
|
||
<name />
|
||
<desc />
|
||
<tail />
|
||
<jumpUrl />
|
||
</namecard>
|
||
</gamecenter>
|
||
<patMsg>
|
||
<chatUser />
|
||
<records>
|
||
<recordNum>0</recordNum>
|
||
</records>
|
||
</patMsg>
|
||
<secretmsg>
|
||
<issecretmsg>0</issecretmsg>
|
||
</secretmsg>
|
||
<websearch />
|
||
</appmsg>";
|
||
|
||
#region xxx
|
||
// return $@"<appmsg appid='' sdkver='0'>
|
||
// <title><![CDATA[兑换成功,请注意查收]]</title>
|
||
// <des><![CDATA[]]</des>
|
||
// <username />
|
||
// <action>view</action>
|
||
// <type>33</type>
|
||
// <showtype>0</showtype>
|
||
// <content />
|
||
// <url />
|
||
// <lowurl />
|
||
// <forwardflag>0</forwardflag>
|
||
// <dataurl />
|
||
// <lowdataurl />
|
||
// <contentattr>0</contentattr>
|
||
// <streamvideo>
|
||
// <streamvideourl />
|
||
// <streamvideototaltime>0</streamvideototaltime>
|
||
// <streamvideotitle />
|
||
// <streamvideowording />
|
||
// <streamvideoweburl />
|
||
// <streamvideothumburl />
|
||
// <streamvideoaduxinfo />
|
||
// <streamvideopublishid />
|
||
// </streamvideo>
|
||
// <canvasPageItem>
|
||
// <canvasPageXml><![CDATA[]]></canvasPageXml>
|
||
// </canvasPageItem>
|
||
// <appattach>
|
||
// <attachid />
|
||
// <cdnthumburl>307f020100047830760201000204d6c63d1d02032f53a10204f0ed7b760204610f5d5304516175706170706d73675f323538663230643164323734356236655f313632383339363838333530365f3533335f61613163303962362d303134322d343032332d383862662d3935373136313536383462380204011800030201000400</cdnthumburl>
|
||
// <cdnthumbmd5>308ac8283026da65a796d699318d218c</cdnthumbmd5>
|
||
// <cdnthumblength>12820</cdnthumblength>
|
||
// <cdnthumbheight>576</cdnthumbheight>
|
||
// <cdnthumbwidth>720</cdnthumbwidth>
|
||
// <cdnthumbaeskey>0487c4db437f564f94d76fc32ca01cd5</cdnthumbaeskey>
|
||
// <aeskey>0487c4db437f564f94d76fc32ca01cd5</aeskey>
|
||
// <encryver>1</encryver>
|
||
// <fileext />
|
||
// <islargefilemsg>0</islargefilemsg>
|
||
// </appattach>
|
||
// <extinfo />
|
||
// <androidsource>3</androidsource>
|
||
// <thumburl>https://fd-1300509451.cos.ap-chengdu.myqcloud.com/fm1.jpeg</thumburl>
|
||
// <mediatagname />
|
||
// <messageaction><![CDATA[]]></messageaction>
|
||
// <messageext><![CDATA[]]></messageext>
|
||
// <emoticongift>
|
||
// <packageflag>0</packageflag>
|
||
// <packageid />
|
||
// </emoticongift>
|
||
// <emoticonshared>
|
||
// <packageflag>0</packageflag>
|
||
// <packageid />
|
||
// </emoticonshared>
|
||
// <designershared>
|
||
// <designeruin>0</designeruin>
|
||
// <designername>null</designername>
|
||
// <designerrediretcturl>null</designerrediretcturl>
|
||
// </designershared>
|
||
// <emotionpageshared>
|
||
// <tid>0</tid>
|
||
// <title>null</title>
|
||
// <desc>null</desc>
|
||
// <iconUrl>null</iconUrl>
|
||
// <secondUrl />
|
||
// <pageType>0</pageType>
|
||
// </emotionpageshared>
|
||
// <webviewshared>
|
||
// <shareUrlOriginal />
|
||
// <shareUrlOpen />
|
||
// <jsAppId />
|
||
// <publisherId />
|
||
// </webviewshared>
|
||
// <template_id />
|
||
// <md5>308ac8283026da65a796d699318d218c</md5>
|
||
// <weappinfo>
|
||
// <pagepath><![CDATA[{target}]]></pagepath>
|
||
// <username><![CDATA[{appname}@app]]></username>
|
||
// <appid><![CDATA[{appid}]]></appid>
|
||
// <type>2</type>
|
||
// <appservicetype>0</appservicetype>
|
||
// <secflagforsinglepagemode>0</secflagforsinglepagemode>
|
||
// <videopageinfo>
|
||
// <thumbwidth>720</thumbwidth>
|
||
// <thumbheight>576</thumbheight>
|
||
// <fromopensdk>0</fromopensdk>
|
||
// </videopageinfo>
|
||
// </weappinfo>
|
||
// <statextstr />
|
||
// <musicShareItem>
|
||
// <musicDuration>0</musicDuration>
|
||
// </musicShareItem>
|
||
// <findernamecard>
|
||
// <username />
|
||
// <avatar><![CDATA[]]></avatar>
|
||
// <nickname />
|
||
// <auth_job />
|
||
// <auth_icon>0</auth_icon>
|
||
// <auth_icon_url />
|
||
// </findernamecard>
|
||
// <finderGuarantee>
|
||
// <scene><![CDATA[0]]></scene>
|
||
// </finderGuarantee>
|
||
// <directshare>0</directshare>
|
||
// <gamecenter>
|
||
// <namecard>
|
||
// <iconUrl />
|
||
// <name />
|
||
// <desc />
|
||
// <tail />
|
||
// <jumpUrl />
|
||
// </namecard>
|
||
// </gamecenter>
|
||
// <patMsg>
|
||
// <chatUser />
|
||
// <records>
|
||
// <recordNum>0</recordNum>
|
||
// </records>
|
||
// </patMsg>
|
||
// <secretmsg>
|
||
// <issecretmsg>0</issecretmsg>
|
||
// </secretmsg>
|
||
// <websearch />
|
||
//</appmsg>";
|
||
#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;
|
||
}
|
||
|
||
|
||
/// <summary>
|
||
/// 缓存是否存在
|
||
/// </summary>
|
||
/// <param name="robotname"></param>
|
||
/// <param name="username"></param>
|
||
/// <param name="text"></param>
|
||
/// <returns></returns>
|
||
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;
|
||
}
|
||
|
||
/// <summary>
|
||
/// 设置缓存(辅助输入)
|
||
/// </summary>
|
||
/// <param name="robotname"></param>
|
||
/// <param name="username"></param>
|
||
/// <param name="text"></param>
|
||
/// <returns></returns>
|
||
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;
|
||
}
|
||
|
||
|
||
/// <summary>
|
||
/// 设置缓存(辅助输入)
|
||
/// </summary>
|
||
/// <param name="robotname"></param>
|
||
/// <param name="username"></param>
|
||
/// <param name="text"></param>
|
||
/// <returns></returns>
|
||
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)
|
||
{ }
|
||
}
|
||
|
||
/// <summary>
|
||
/// MD5字符串加密
|
||
/// </summary>
|
||
/// <param name="txt"></param>
|
||
/// <returns>加密后字符串</returns>
|
||
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<string, object> ReadConfig(string name, bool refresh = false)
|
||
{
|
||
return Util.Read<Dictionary<string, object>>(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<string, string> DecodeQRCodeCache = new Dictionary<string, string>();
|
||
|
||
/// <summary>
|
||
/// 二维码解析类型
|
||
/// </summary>
|
||
public enum DecodeQRCodeType
|
||
{
|
||
全部 = 0,
|
||
Zxing = 1,
|
||
ThoughtWorks = 2,
|
||
Caoliao = 3,
|
||
}
|
||
|
||
/// <summary>
|
||
/// 解密二维码
|
||
/// </summary>
|
||
/// <param name="filename">文件路径</param>
|
||
/// <returns></returns>
|
||
[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<string, object>;
|
||
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<string, object>;
|
||
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;
|
||
}
|
||
|
||
/// <summary>
|
||
/// 通过FileStream 来打开文件,这样就可以实现不锁定Image文件,到时可以让多用户同时访问Image文件
|
||
/// </summary>
|
||
/// <param name="path"></param>
|
||
/// <returns></returns>
|
||
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";
|
||
}
|
||
|
||
/// <summary>
|
||
/// 解析二维码
|
||
/// </summary>
|
||
/// <param name="bitmap"></param>
|
||
/// <returns></returns>
|
||
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
|
||
|
||
/// <summary>
|
||
/// 生成指定位数的随机数
|
||
/// </summary>
|
||
/// <param name="iLength"></param>
|
||
/// <returns></returns>
|
||
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;
|
||
}
|
||
|
||
/// <summary>
|
||
/// 添加水印
|
||
/// </summary>
|
||
/// <param name="imgPath">原图片地址</param>
|
||
/// <param name="sImgPath">水印图片地址</param>
|
||
/// <returns>resMsg[0] 成功,失败 </returns>
|
||
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;
|
||
}
|
||
|
||
/// <summary>
|
||
/// 给图片添加文字水印
|
||
/// </summary>
|
||
/// <param name="img">图片</param>
|
||
/// <param name="text">文字</param>
|
||
/// <param name="p">文本位置中心点坐标</param>
|
||
/// <param name="font">字体</param>
|
||
/// <param name="fontColor">字体颜色</param>
|
||
/// <param name="angle">旋转角度(顺时针)</param>
|
||
/// <returns></returns>
|
||
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,在邮箱是这样显示的,[发件人:小明<panthervic@163.com>;]
|
||
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";
|
||
/// <summary>
|
||
/// 10进制转换为62进制
|
||
/// </summary>
|
||
/// <param name="id"></param>
|
||
/// <returns></returns>
|
||
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<T>(string value)
|
||
{
|
||
var v = Enum.Parse(typeof(T), value);
|
||
return (T)v;
|
||
}
|
||
public static T ConvertEnum<T>(int value)
|
||
{
|
||
return (T)Enum.Parse(typeof(T), value.ToString());
|
||
}
|
||
public static T ConvertEnum<T>(ushort value)
|
||
{
|
||
return (T)Enum.Parse(typeof(T), value.ToString());
|
||
}
|
||
/// <summary>
|
||
/// 读取配置文件
|
||
/// </summary>
|
||
/// <typeparam name="T"></typeparam>
|
||
public static T Read<T>(string name = "")
|
||
{
|
||
var obj = System.Activator.CreateInstance<T>();
|
||
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<T>(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<T>(json);
|
||
}
|
||
catch (Exception)
|
||
{ }
|
||
}
|
||
return default(T);
|
||
}
|
||
|
||
/// <summary>
|
||
/// 将图片转换为字节数组
|
||
/// </summary>
|
||
/// <param name="imagePath">完整的图片路径</param>
|
||
/// <returns></returns>
|
||
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;
|
||
|
||
}
|
||
|
||
/// <summary>
|
||
/// 将图片Bitmap类型转成字节数组
|
||
/// </summary>
|
||
/// <param name="bmp"></param>
|
||
/// <returns></returns>
|
||
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;
|
||
}
|
||
|
||
/// <summary>
|
||
/// 获取一个淘口令前后随机修饰符
|
||
/// </summary>
|
||
/// <param name="str">要随机的修饰符</param>
|
||
/// <param name="separator">分隔符,默认'|'</param>
|
||
/// <returns>返回随机的一个修饰符或传入的str值</returns>
|
||
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();
|
||
|
||
/// <summary>
|
||
/// 保存配置文件
|
||
/// </summary>
|
||
/// <param name="obj"></param>
|
||
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();
|
||
}
|
||
}
|
||
/// <summary>
|
||
/// 图像灰度化
|
||
/// </summary>
|
||
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<T>(string content)
|
||
{
|
||
JavaScriptSerializer serializer = new JavaScriptSerializer();
|
||
serializer.MaxJsonLength = Int32.MaxValue;
|
||
return serializer.Deserialize<T>(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;
|
||
}
|
||
|
||
/// <summary>
|
||
/// 下载文件
|
||
/// </summary>
|
||
/// <param name="URL">下载文件地址</param>
|
||
/// <param name="Filename">下载后的存放地址</param>
|
||
/// <param name="Prog">用于显示的进度条</param>
|
||
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;
|
||
}
|
||
}
|
||
|
||
/// <summary>
|
||
/// 下载HTML
|
||
/// </summary>
|
||
/// <param name="url">地址</param>
|
||
/// <param name="data">Post参数</param>
|
||
/// <returns></returns>
|
||
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;
|
||
|
||
}
|
||
|
||
/// <summary>
|
||
/// 读取数据
|
||
/// </summary>
|
||
/// <param name="path">文件路径</param>
|
||
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 操作
|
||
|
||
/// <summary>
|
||
/// 设置IE
|
||
/// </summary>
|
||
/// <param name="hInternet">hInternet</param>
|
||
/// <param name="dwOption">dwOption</param>
|
||
/// <param name="lpBuffer">lpBuffer</param>
|
||
/// <param name="lpdwBufferLength">lpdwBufferLength</param>
|
||
/// <returns>处理结果</returns>
|
||
[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) { }
|
||
}
|
||
|
||
/// <summary>
|
||
/// 拷贝oldlab的文件到newlab下面
|
||
/// </summary>
|
||
/// <param name="sourcePath">lab文件所在目录(@"~\labs\oldlab")</param>
|
||
/// <param name="savePath">保存的目标目录(@"~\labs\newlab")</param>
|
||
/// <returns>返回:true-拷贝成功;false:拷贝失败</returns>
|
||
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;
|
||
}
|
||
/// <summary>
|
||
/// 删除历史记录 Win7+ 需要管理员权限
|
||
/// </summary>
|
||
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");
|
||
}
|
||
/// <summary>
|
||
/// 调用CMD执行命令
|
||
/// </summary>
|
||
/// <param name="cmd"></param>
|
||
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");
|
||
}
|
||
|
||
/// <summary>
|
||
/// 删除一个文件,System.IO.File.Delete()函数不可以删除只读文件,这个函数可以强行把只读文件删除。
|
||
/// </summary>
|
||
/// <param name="path">文件路径</param>
|
||
/// <returns>成功为true</returns>
|
||
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;
|
||
}
|
||
/// <summary>
|
||
/// 删除文件夹
|
||
/// </summary>
|
||
/// <param name="path">文件夹路径</param>
|
||
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
|
||
|
||
}
|
||
|
||
}
|
||
/// <summary>
|
||
/// 删除临时文件 Win7+ 需要管理员权限
|
||
/// </summary>
|
||
public static void CleanTempFiles()
|
||
{
|
||
FolderClear(Environment.GetFolderPath(Environment.SpecialFolder.InternetCache));
|
||
RunCmd("RunDll32.exe InetCpl.cpl,ClearMyTracksByProcess 8");
|
||
}
|
||
/// <summary>
|
||
/// 删除Cookie文件 Win7+ 需要管理员权限
|
||
/// </summary>
|
||
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
|
||
|
||
/// <summary>
|
||
/// 是否为XML
|
||
/// </summary>
|
||
/// <param name="mess"></param>
|
||
/// <returns></returns>
|
||
public static bool IsXML(string mess)
|
||
{
|
||
return mess.Contains("<?xml") || mess.Contains("<msg><emoji") || mess.Contains("<appmsg appid=");
|
||
}
|
||
|
||
/// <summary>
|
||
/// 读文件到byte[]
|
||
/// </summary>
|
||
/// <param name="fileName">硬盘文件路径</param>
|
||
/// <returns></returns>
|
||
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();
|
||
}
|
||
}
|
||
|
||
/// <summary>
|
||
/// 写byte[]到fileName
|
||
/// </summary>
|
||
/// <param name="pReadByte">byte[]</param>
|
||
/// <param name="fileName">保存至硬盘路径</param>
|
||
/// <returns></returns>
|
||
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<fl_adzone_group>("select * from fl_adzone_group").Count();
|
||
if (count != 0) return true;
|
||
|
||
var ShowTgwz = AppConfig_GetValue("ShowTgwz");
|
||
return (ShowTgwz != null && ShowTgwz == "1");
|
||
}
|
||
|
||
/// <summary>
|
||
/// 文件转换成Base64字符串
|
||
/// </summary>
|
||
/// <param name="fileName">文件绝对路径</param>
|
||
/// <returns></returns>
|
||
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;
|
||
}
|
||
|
||
/// <summary>
|
||
/// Base64字符串转换成文件
|
||
/// </summary>
|
||
/// <param name="strInput">base64字符串</param>
|
||
/// <param name="fileName">保存文件的绝对路径</param>
|
||
/// <returns></returns>
|
||
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;
|
||
}
|
||
|
||
/// <summary>
|
||
/// 将图片控制在宽度为指定得像素
|
||
/// </summary>
|
||
/// <param name="srcImage"></param>
|
||
/// <param name="size"></param>
|
||
/// <returns></returns>
|
||
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;
|
||
}
|
||
}
|
||
|
||
/// <summary>
|
||
/// 将图片按百分比压缩,
|
||
/// </summary>
|
||
/// <param name="iSource"></param>
|
||
/// <param name="outPath"></param>
|
||
/// <param name="flag">flag取值1到100,越小压缩比越大</param>
|
||
/// <returns></returns>
|
||
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();
|
||
}
|
||
|
||
|
||
/// <summary>
|
||
/// 日期转换成时间戳Timestamp
|
||
/// </summary>
|
||
/// <param name="timeStamp"></param>
|
||
/// <returns></returns>
|
||
public static long GetTimeSpan(DateTime time)
|
||
{
|
||
DateTime dtStart = TimeZone.CurrentTimeZone.ToLocalTime(new DateTime(1970, 1, 1));
|
||
|
||
return (long)(time - dtStart).TotalMilliseconds;
|
||
}
|
||
|
||
/// <summary>
|
||
/// 日期转换成时间戳Timestamp
|
||
/// </summary>
|
||
/// <param name="timeStamp"></param>
|
||
/// <returns></returns>
|
||
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;
|
||
}
|
||
|
||
/// <summary>
|
||
/// 时间戳转时间
|
||
/// </summary>
|
||
/// <param name="timeSpan"></param>
|
||
/// <returns></returns>
|
||
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);
|
||
}
|
||
|
||
/// <summary>
|
||
/// 获取UUID
|
||
/// </summary>
|
||
/// <returns></returns>
|
||
public static string GetUUID()
|
||
{
|
||
return System.Guid.NewGuid().ToString("N");
|
||
}
|
||
|
||
#region 加密
|
||
//默认密钥向量
|
||
private static byte[] Keys = { 0x42, 0x34, 0x56, 0x3C, 0x90, 0xAB, 0xAD, 0xEE };
|
||
|
||
//// <summary>
|
||
/// DES加密字符串
|
||
/// </summary>
|
||
/// <param name="encryptString">待加密的字符串</param>
|
||
/// <param name="encryptKey">加密密钥,要求为8位</param>
|
||
/// <returns>加密成功返回加密后的字符串,失败返回源串</returns>
|
||
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;
|
||
}
|
||
}
|
||
|
||
//// <summary>
|
||
/// DES解密字符串
|
||
/// </summary>
|
||
/// <param name="decryptString">待解密的字符串</param>
|
||
/// <param name="decryptKey">解密密钥,要求为8位,和加密密钥相同</param>
|
||
/// <returns>解密成功返回解密后的字符串,失败返源串</returns>
|
||
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
|
||
{
|
||
/// <summary>
|
||
/// 将枚举转为集合
|
||
/// </summary>
|
||
/// <typeparam name="T"></typeparam>
|
||
/// <returns></returns>
|
||
public static List<EnumEntity> EnumToList<T>()
|
||
{
|
||
List<EnumEntity> list = new List<EnumEntity>();
|
||
|
||
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;
|
||
}
|
||
|
||
/// <summary>
|
||
/// 获取枚举描述
|
||
/// </summary>
|
||
/// <typeparam name="T"></typeparam>
|
||
/// <param name="EnumName"></param>
|
||
/// <returns></returns>
|
||
public static string GetEnumDesction<T>(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 "";
|
||
}
|
||
}
|
||
|
||
/// <summary>
|
||
/// 枚举实体
|
||
/// </summary>
|
||
public class EnumEntity
|
||
{
|
||
/// <summary>
|
||
/// 枚举的描述
|
||
/// </summary>
|
||
public string Desction { set; get; }
|
||
|
||
/// <summary>
|
||
/// 枚举名称
|
||
/// </summary>
|
||
public string EnumName { set; get; }
|
||
|
||
/// <summary>
|
||
/// 枚举对象的值
|
||
/// </summary>
|
||
public int EnumValue { set; get; }
|
||
}
|
||
}
|