c#的各种方法
(一)图片转base64字符串
string fromImagePath="图片路径";
Bitmap bit = (Bitmap)Bitmap.FromFile(fromImagePath, false);
System.IO.MemoryStream ms = new System.IO.MemoryStream();
bit .Save(ms, System.Drawing.Imaging.ImageFormat.Png);
string base64Img = Convert.ToBase64String(ms.ToArray());
newBit.Dispose();
(二)获取枚举描述
public static string GetEnumDesc<T>(Object obj)
{
try
{
obj = (T)obj;
if (obj == null) return "";
if (!obj.GetType().IsEnum) return "";
FieldInfo fieldinfo = obj.GetType().GetField(obj.ToString());
string str = string.Empty;
if (fieldinfo == null) {
return "";
}
Object[] objs = fieldinfo.GetCustomAttributes(typeof(DescriptionAttribute), false);
if (objs != null && objs.Length != 0)
{
DescriptionAttribute des = (DescriptionAttribute)objs[0];
str = des.Description;
}
return str;
}
catch {
return "";
}
}
(三)获取枚举数据列表
public static List<EnumModel> GetEnumList(Type enumType)
{
List<EnumModel> list = new List<EnumModel>();
var arr2 = enumType.GetFields();
for (int i = 0; i < arr2.Length; i++)
{
var item = arr2[i];
System.ComponentModel.DescriptionAttribute[] dd = item.GetCustomAttributes(typeof(System.ComponentModel.DescriptionAttribute), true) as System.ComponentModel.DescriptionAttribute[];
if (dd.Length > 0) {
string des = dd[0].Description;
var name = item.Name;
int num = (int)Enum.Parse(enumType, name);
list.Add(new EnumModel(des, name, num));
}
}
return list;
}
public class EnumModel{
public EnumModel(string _Des,string _Name,int _Value) {
Des = _Des;
Name = _Name;
Value = _Value;
}
public string Des { set; get; }
public string Name { set; get; }
public int Value { set; get; }
}
(四)添加缓存数据
object objLock = "0";
string strKey = "cachekey";
Cache cache = HttpRuntime.Cache;
object objAll = null;
try {
objAll = cache.Get(strKey);
}
catch (Exception) { objAll = null; }
if (objAll == null || string.IsNullOrEmpty(objAll.ToString())){
cache.Insert(strKey, "data", null, DateTime.UtcNow.AddHours(6), System.Web.Caching.Cache.NoSlidingExpiration);
}
(五)获取dynamic内的字段值
dynamic attr = new {MemberID=1};
int MemberID = attr.GetType().GetProperty("MemberID").GetValue(attr, null)
(六)单变量数组去重
List<int> intList=new List<int>(){1,1,2,3,4,5,6,6};
intList= intList.Where((x, i) => intList.FindIndex(z => z == x) == i).ToList();
(七)word转pdf
①.引用Aspose.Words.dll 网盘的学术>.NET word和excel转pdf dll>Aspose.Words18.4破解版.rar
②.引用SkiaSharp、System.Text.Encoding.CodePages、System.Drawing.Common nuget找
public static void WordToPDF(string wordPath, string pdfPath)
{
//Aspose.Words.License lic = new Aspose.Words.License();
//lic.SetLicense("Aspose.Total.lic");破解版不用设置license
//打开word文件
Document doc = new Aspose.Words.Document(wordPath);
//验证参数
if (doc == null) { throw new Exception("Word文件无效"); }
doc.Save(pdfPath, Aspose.Words.SaveFormat.Pdf);//还可以改成其它格式
}
当报
No data is available for encoding 1252.
错误时,在读取excel前加上
Encoding.RegisterProvider(CodePagesEncodingProvider.Instance);//注册EncodeProvider
(八)excel转pdf
①.引用Aspose.Cell.dll 网盘的学术>.NET word和excel转pdf dll>Aspose.Cells+18.4.7z
②.引用SkiaSharp、System.Text.Encoding.CodePages、System.Drawing.Common nuget找
public static string ExcelToPDF(string execlPath, string pdfName)
{
Aspose.Cells.Workbook ewb = new Aspose.Cells.Workbook(execlPath);
foreach (Aspose.Cells.Worksheet item in ewb.Worksheets)
{
item.PageSetup.PaperSize = Aspose.Cells.PaperSizeType.PaperA4;item.PageSetup.Zoom = 98;//打印时页面设置,缩放比例
item.PageSetup.LeftMargin = 0; //左边距为0
item.PageSetup.RightMargin = 0; //右边距为0
item.PageSetup.CenterHorizontally = true;//水平居中
}
ewb.Save(pdfName, Aspose.Cells.SaveFormat.Pdf);
return pdfName;
}
当报
No data is available for encoding 1252.
错误时,在读取excel前加上
Encoding.RegisterProvider(CodePagesEncodingProvider.Instance);//注册EncodeProvider
(九)深度克隆
/// <summary>
/// 对象克隆扩展方法
/// </summary>
public static class CSFrameworkCloneExtends
{
/// <summary>
/// 深度克隆对象列表
/// </summary>
/// <param name="objs"></param>
/// <returns></returns>
public static IList CloneDeeply(this IList objs)
{
ArrayList list = new ArrayList();
foreach (object o in objs)
{
list.Add(CloneDeeply(o));
}
return list;
}
/// <summary>
/// 深度拷贝(使用.NET反射+递归原理实现对象深度克隆)
/// </summary>
/// <param name="obj"></param>
/// <returns></returns>
public static object CloneDeeply(this object obj)
{
object o = System.Activator.CreateInstance(obj.GetType()); //实例化一个T类型对象
PropertyInfo[] propertyInfos = obj.GetType().GetProperties(); //获取T对象的所有公共属性
foreach (PropertyInfo propertyInfo in propertyInfos)
{
object propertyValue = propertyInfo.GetValue(obj, null);
if (propertyValue != null)
{
//判断值是否为空,如果空赋值为null
if (propertyInfo.PropertyType.IsGenericType && propertyInfo.PropertyType.GetGenericTypeDefinition().Equals(typeof(Nullable<>)))
{
//如果convertsionType为nullable类,声明一个NullableConverter类,该类提供从Nullable类到基础基元类型的转换
NullableConverter nullableConverter = new NullableConverter(propertyInfo.PropertyType);
//将convertsionType转换为nullable对的基础基元类型
propertyInfo.SetValue(o, Convert.ChangeType(propertyInfo.GetValue(obj), nullableConverter.UnderlyingType), null);
}
else
{
//支持克隆
if (propertyValue is ICloneable)
{
//将convertsionType转换为nullable对的基础基元类型
propertyInfo.SetValue(o, Convert.ChangeType((propertyValue as ICloneable).Clone(), propertyInfo.PropertyType), null);
}
else
{
object value;
if (propertyValue is IList) //是列表对象
value = CloneList(propertyValue as IList, propertyInfo.PropertyType);
else
value = propertyValue;
propertyInfo.SetValue(o, value, null);
}
}
}
}
return o;
}
/// <summary>
/// 克隆对象列表
/// </summary>
/// <param name="list"></param>
/// <param name="listType"></param>
/// <returns></returns>
private static IList CloneList(IList list, Type listType)
{
IList ret = (IList)System.Activator.CreateInstance(listType);
foreach (object obj in list)
{
ret.Add(obj.CloneDeeply());
}
return ret;
}
}
(十)Console调用接口
var url = "/dict/test";
var params = {advertiserUid: 1232131, advertiserWeiboNickname: "18"};
var xhr = new XMLHttpRequest();
xhr.open("POST", url, true);
xhr.setRequestHeader("Content-Type", "application/json");
xhr.onload = function (e) {
if (xhr.readyState === 4) {
if (xhr.status === 200) {
console.log(xhr.responseText);
} else {
console.error(xhr.statusText);
}
}
};
xhr.onerror = function (e) {
console.error(xhr.statusText);
};
xhr.send(JSON.stringify(params));
(十一)string转int[]
int[] SkinArrya = Array.ConvertAll<string, int>(a.RoleIds.Trim(',').Split(','), s => int.Parse(s));
(十二)使用工作队列多线程处理批量任务
ThreadPool.SetMinThreads(50, 50);
System.Threading.ThreadPool.SetMaxThreads(50, 50);
object param="参数";
for(int i=0;i<=1000;i++){
ThreadPool.QueueUserWorkItem(new System.Threading.WaitCallback(ThreadHandle),param);
}
public static void ThreadHandle(object param){
Console.WriteLine("线程id:"+Thread.CurrentThread.ManagedThreadId+";"+param.ToString());
}
上面为.net自带的调用方法,缺陷是设置了最大最小线程后,全局能使用的线程就只有这些,所以也可以调用SmartThreadPool 这个工具,他调用线程时只是局部的不是全局
private static SmartThreadPool smartThreadPool => new SmartThreadPool(new STPStartInfo() { MinWorkerThreads = 50, MaxWorkerThreads = 50, AreThreadsBackground = true });
smartThreadPool.QueueWorkItem(new Amib.Threading.WorkItemCallback(ThreadHandle),param);
(十三)计算文件hash值
/// <summary>
/// 提供用于计算指定文件哈希值的方法
/// <example>例如计算文件的MD5值:
/// <code>
/// String hashMd5=HashHelper.ComputeMD5("MyFile.txt");
/// </code>
/// </example>
/// <example>例如计算文件的CRC32值:
/// <code>
/// String hashCrc32 = HashHelper.ComputeCRC32("MyFile.txt");
/// </code>
/// </example>
/// <example>例如计算文件的SHA1值:
/// <code>
/// String hashSha1 =HashHelper.ComputeSHA1("MyFile.txt");
/// </code>
/// </example>
/// </summary>
public sealed class HashHelper
{
/// <summary>
/// 计算指定文件的MD5值
/// </summary>
/// <param name="fileName">指定文件的完全限定名称</param>
/// <returns>返回值的字符串形式</returns>
public static String ComputeMD5(String fileName)
{
String hashMD5 = String.Empty;
//检查文件是否存在,如果文件存在则进行计算,否则返回空值
if (System.IO.File.Exists(fileName))
{
using (System.IO.FileStream fs = new System.IO.FileStream(fileName, System.IO.FileMode.Open, System.IO.FileAccess.Read))
{
//计算文件的MD5值
System.Security.Cryptography.MD5 calculator=System.Security.Cryptography.MD5.Create();
Byte[] buffer = calculator.ComputeHash(fs);
calculator.Clear();
//将字节数组转换成十六进制的字符串形式
StringBuilder stringBuilder = new StringBuilder();
for (int i = 0; i < buffer.Length; i++)
{
stringBuilder.Append(buffer[i].ToString("x2"));
}
hashMD5= stringBuilder.ToString();
}//关闭文件流
}//结束计算
return hashMD5;
}//ComputeMD5
/// <summary>
/// 计算指定文件的CRC32值
/// </summary>
/// <param name="fileName">指定文件的完全限定名称</param>
/// <returns>返回值的字符串形式</returns>
public static String ComputeCRC32(String fileName)
{
String hashCRC32 = String.Empty;
//检查文件是否存在,如果文件存在则进行计算,否则返回空值
if (System.IO.File.Exists(fileName))
{
using (System.IO.FileStream fs = new System.IO.FileStream(fileName, System.IO.FileMode.Open, System.IO.FileAccess.Read))
{
//计算文件的CSC32值
Crc32 calculator = new Crc32();
Byte[] buffer = calculator.ComputeHash(fs);
calculator.Clear();
//将字节数组转换成十六进制的字符串形式
StringBuilder stringBuilder = new StringBuilder();
for (int i = 0; i < buffer.Length; i++)
{
stringBuilder.Append(buffer[i].ToString("x2"));
}
hashCRC32 = stringBuilder.ToString();
}//关闭文件流
}
return hashCRC32;
}//ComputeCRC32
/// <summary>
/// 计算指定文件的SHA1值
/// </summary>
/// <param name="fileName">指定文件的完全限定名称</param>
/// <returns>返回值的字符串形式</returns>
public static String ComputeSHA1(String fileName)
{
String hashSHA1 = String.Empty;
//检查文件是否存在,如果文件存在则进行计算,否则返回空值
if (System.IO.File.Exists(fileName))
{
using (System.IO.FileStream fs = new System.IO.FileStream(fileName, System.IO.FileMode.Open, System.IO.FileAccess.Read))
{
//计算文件的SHA1值
System.Security.Cryptography.SHA1 calculator = System.Security.Cryptography.SHA1.Create();
Byte[] buffer = calculator.ComputeHash(fs);
calculator.Clear();
//将字节数组转换成十六进制的字符串形式
StringBuilder stringBuilder = new StringBuilder();
for (int i = 0; i < buffer.Length; i++)
{
stringBuilder.Append(buffer[i].ToString("x2"));
}
hashSHA1 = stringBuilder.ToString();
}//关闭文件流
}
return hashSHA1;
}//ComputeSHA1
}//end class: HashHelper
/// <summary>
/// 提供 CRC32 算法的实现
/// </summary>
public class Crc32 : System.Security.Cryptography.HashAlgorithm
{
public const UInt32 DefaultPolynomial = 0xedb88320;
public const UInt32 DefaultSeed = 0xffffffff;
private UInt32 hash;
private UInt32 seed;
private UInt32[] table;
private static UInt32[] defaultTable;
public Crc32()
{
table = InitializeTable(DefaultPolynomial);
seed = DefaultSeed;
Initialize();
}
public Crc32(UInt32 polynomial, UInt32 seed)
{
table = InitializeTable(polynomial);
this.seed = seed;
Initialize();
}
public override void Initialize()
{
hash = seed;
}
protected override void HashCore(byte[] buffer, int start, int length)
{
hash = CalculateHash(table, hash, buffer, start, length);
}
protected override byte[] HashFinal()
{
byte[] hashBuffer = UInt32ToBigEndianBytes(~hash);
this.HashValue = hashBuffer;
return hashBuffer;
}
public static UInt32 Compute(byte[] buffer)
{
return ~CalculateHash(InitializeTable(DefaultPolynomial), DefaultSeed, buffer, 0, buffer.Length);
}
public static UInt32 Compute(UInt32 seed, byte[] buffer)
{
return ~CalculateHash(InitializeTable(DefaultPolynomial), seed, buffer, 0, buffer.Length);
}
public static UInt32 Compute(UInt32 polynomial, UInt32 seed, byte[] buffer)
{
return ~CalculateHash(InitializeTable(polynomial), seed, buffer, 0, buffer.Length);
}
private static UInt32[] InitializeTable(UInt32 polynomial)
{
if (polynomial == DefaultPolynomial && defaultTable != null)
{
return defaultTable;
}
UInt32[] createTable = new UInt32[256];
for (int i = 0; i < 256; i++)
{
UInt32 entry = (UInt32)i;
for (int j = 0; j < 8; j++)
{
if ((entry & 1) == 1)
entry = (entry >> 1) ^ polynomial;
else
entry = entry >> 1;
}
createTable[i] = entry;
}
if (polynomial == DefaultPolynomial)
{
defaultTable = createTable;
}
return createTable;
}
private static UInt32 CalculateHash(UInt32[] table, UInt32 seed, byte[] buffer, int start, int size)
{
UInt32 crc = seed;
for (int i = start; i < size; i++)
{
unchecked
{
crc = (crc >> 8) ^ table[buffer[i] ^ crc & 0xff];
}
}
return crc;
}
private byte[] UInt32ToBigEndianBytes(UInt32 x)
{
return new byte[] { (byte)((x >> 24) & 0xff), (byte)((x >> 16) & 0xff), (byte)((x >> 8) & 0xff), (byte)(x & 0xff) };
}
}//end class: Crc32
(十四)查找证书
public class MakecertHelper
{
/// <summary>
/// 根据私钥证书得到证书实体,得到实体后可以根据其公钥和私钥进行加解密
/// 加解密函数使用DEncrypt的RSACryption类
/// </summary>
/// <param name="pfxFileName"></param>
/// <param name="password"></param>
/// <returns></returns>
public static X509Certificate2 GetCertificateFromPfxFile(string pfxFileName,
string password)
{
try
{
return new X509Certificate2(pfxFileName, password, X509KeyStorageFlags.Exportable);
}
catch (Exception e)
{
return null;
}
}
/// <summary>
/// 从证书存储区读取证书
/// </summary>
/// <returns></returns>
public static X509Certificate2 GetCertificateFromHost()
{
X509Store store = new X509Store("MY", StoreLocation.CurrentUser);
store.Open(OpenFlags.OpenExistingOnly | OpenFlags.ReadWrite);
X509Certificate2Collection fcollection = (X509Certificate2Collection)store.Certificates;
//X509Certificate2Collection collection = X509Certificate2UI.SelectFromCollection(fcollection, "Select an X509 Certificate", "Choose a certificate to examine.", X509SelectionFlag.MultiSelection);//弹出框,可以选择需要的证书
X509Certificate2Collection findResult = fcollection.Find(X509FindType.FindBySerialNumber, "5ffc9b11f01b6c83416903a105a43e99", false);//有多个重载,可以用不同的方法查询,此类型为用序列号查询证书
return findResult[0];
}
}
(十五)接受文件
IFormFileCollection files = Request.Form.Files;
(16)提交文件
MultipartFormDataContent multiContent = new MultipartFormDataContent()
{
{ new StringContent(idCard), "idCard"},//传输字符串
{ new ByteArrayContent(System.IO.File.ReadAllBytes(filePath)), "file", Path.GetFileName(filePath)},//传输文件
};
var response = await PostFile(url, multiContent, true);
public async Task<string> PostFile(string url, MultipartFormDataContent multiContent)
{
string json = "";
try
{
var response = await _client.PostAsync(url, multiContent);
response.EnsureSuccessStatusCode();
json = await response.Content.ReadAsStringAsync();
}
catch (Exception ex)
{
throw ex;
}
return json;
}
(十六)获取文件
private async Task<Stream> GetFileAsync(string url)
{
Stream stream;
try
{
var response = await _client.GetAsync(_appDomian + url);
response.EnsureSuccessStatusCode();
stream = await response.Content.ReadAsStreamAsync();
}
catch (Exception ex)
{
throw ex;
}
return stream;
}
//调用并保存文件
Stream stream = GetFileAsync(url).Result;
byte[] bytes = new byte[stream.Length];
stream.Read(bytes, 0, bytes.Length);
stream.Close();
FileStream fs = new FileStream(savePath, FileMode.Create);
BinaryWriter bw = new BinaryWriter(fs);
bw.Write(bytes);
bw.Close();
fs.Close();
(十七)图片等比缩放类
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Drawing.Imaging;
namespace Maticsoft.Common.Extension
{
/// <summary>
/// 图片缩放
/// </summary>
public class ImgZooming
{
System.IO.FileStream fs;
System.Drawing.Image initImage;
string ofilename;
/// <summary>
/// 初始化,创建原始图片对象
/// </summary>
/// <param name="filepath">原图地址</param>
public ImgZooming(string filepath)
{
if (!System.IO.File.Exists(filepath))
{
fs = null;
return;
}
//原始图片(获取原始图片创建对象,并使用流中嵌入的颜色管理信息)
fs = new System.IO.FileStream(filepath, System.IO.FileMode.Open);
initImage = System.Drawing.Image.FromStream(fs, true);
ofilename = filepath.Substring(filepath.LastIndexOf("\\")+1);
}
/// <summary>
/// 释放资源
/// </summary>
public void Dispose()
{
if (fs == null)
return;
initImage.Dispose();
fs.Dispose();
}
/// <summary>
/// 图片缩放,按比例存储缩略图(不裁剪)
/// </summary>
/// <param name="savePath">缩略图存放地址</param>
/// <param name="width">缩略图最大宽度</param>
/// <param name="height">缩略图最大高度</param>
/// <param name="filename">重命名,带扩展名</param>
public void ZoomAuto(string savePath, int width, int height, string filename="",string extand="jpg")
{
if (fs == null)
return;
//如存放地址不存在,创建地址
if (!Directory.Exists(savePath))
Directory.CreateDirectory(savePath);
if (File.Exists(savePath + filename))
File.Delete(savePath+filename);
System.Drawing.Image newImage;
System.Drawing.Graphics newG;
try
{
if (width > 0 && height > 0)
{
//原始图片写入画布坐标和宽高(用来设置裁减溢出部分)
int x = 0;
int y = 0;
int ow = initImage.Width;
int oh = initImage.Height;
//原始图片画布,设置写入缩略图画布坐标和宽高(用来原始图片整体宽高缩放)
int bg_x = 0;
int bg_y = 0;
int bg_w = width;
int bg_h = height;
//倍数变量
double multiple = 0;
//获取宽长的或是高长与缩略图的倍数
if (initImage.Width == initImage.Height)
{
double z = (double)(width > height ? height : width);
multiple = (double)initImage.Width / z;
}
else if (initImage.Width > initImage.Height) multiple = (double)initImage.Width / (double)width;
else multiple = (double)initImage.Height / (double)height;
//上传的图片的宽和高小等于缩略图
if (ow <= width && oh <= height)
{
//缩略图按原始宽高
bg_w = initImage.Width;
bg_h = initImage.Height;
//空白部分用背景色填充
bg_x = Convert.ToInt32(((double)width - (double)ow) / 2);
bg_y = Convert.ToInt32(((double)height - (double)oh) / 2);
}
//上传的图片的宽和高大于缩略图
else
{
//宽高按比例缩放
bg_w = Convert.ToInt32((double)initImage.Width / multiple);
bg_h = Convert.ToInt32((double)initImage.Height / multiple);
//空白部分用背景色填充
bg_y = Convert.ToInt32(((double)height - (double)bg_h) / 2);
bg_x = Convert.ToInt32(((double)width - (double)bg_w) / 2);
}
//生成新图
//新建一个bmp图片
newImage = new System.Drawing.Bitmap(width, height);
//新建一个画板
newG = System.Drawing.Graphics.FromImage(newImage);
//设置质量
newG.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic;
newG.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;
//置背景色
newG.Clear(Color.White);
//画图
newG.DrawImage(initImage, new System.Drawing.Rectangle(bg_x, bg_y, bg_w, bg_h), new System.Drawing.Rectangle(x, y, ow, oh), System.Drawing.GraphicsUnit.Pixel);
if (filename == "")
{
filename = ofilename;
}
savePath += filename;
var format=ImageFormat.Jpeg;
switch (extand)
{
case "png": format = ImageFormat.Png; break;
case "gif": format = ImageFormat.Gif; break;
}
newImage.Save(savePath, format);
//释放资源
newG.Dispose();
newImage.Dispose();
}
}
catch(Exception ex)
{
AppLog.Write("生成缩略图报错", AppLog.LogMessageType.Error, ex);
this.Dispose();
}
//释放资源
//initImage.Dispose();
//fs.Dispose();
}
/// <summary>
/// 压缩图片,降低图片质量
/// </summary>
/// <param name="savePath">缩略图存放地址</param>
/// <param name="width">缩略图最大宽度</param>
/// <param name="height">缩略图最大高度</param>
/// <param name="filename">重命名,带扩展名</param>
public void ZoomAuto(string savePath, string filename = "", string extand = "jpg")
{
if (fs == null)
return;
//如存放地址不存在,创建地址
if (!Directory.Exists(savePath))
Directory.CreateDirectory(savePath);
System.Drawing.Image newImage;
System.Drawing.Graphics newG;
int width = initImage.Width;
int height = initImage.Height;
try
{
if (width > 0 && height > 0)
{
//原始图片写入画布坐标和宽高(用来设置裁减溢出部分)
int x = 0;
int y = 0;
int ow = initImage.Width;
int oh = initImage.Height;
//原始图片画布,设置写入缩略图画布坐标和宽高(用来原始图片整体宽高缩放)
int bg_x = 0;
int bg_y = 0;
int bg_w = width;
int bg_h = height;
//倍数变量
double multiple = 0;
//获取宽长的或是高长与缩略图的倍数
if (initImage.Width == initImage.Height)
{
double z = (double)(width > height ? height : width);
multiple = (double)initImage.Width / z;
}
else if (initImage.Width > initImage.Height) multiple = (double)initImage.Width / (double)width;
else multiple = (double)initImage.Height / (double)height;
//上传的图片的宽和高小等于缩略图
if (ow <= width && oh <= height)
{
//缩略图按原始宽高
bg_w = initImage.Width;
bg_h = initImage.Height;
//空白部分用背景色填充
bg_x = Convert.ToInt32(((double)width - (double)ow) / 2);
bg_y = Convert.ToInt32(((double)height - (double)oh) / 2);
}
//上传的图片的宽和高大于缩略图
else
{
//宽高按比例缩放
bg_w = Convert.ToInt32((double)initImage.Width / multiple);
bg_h = Convert.ToInt32((double)initImage.Height / multiple);
//空白部分用背景色填充
bg_y = Convert.ToInt32(((double)height - (double)bg_h) / 2);
bg_x = Convert.ToInt32(((double)width - (double)bg_w) / 2);
}
//生成新图
//新建一个bmp图片
newImage = new System.Drawing.Bitmap(width, height);
//新建一个画板
newG = System.Drawing.Graphics.FromImage(newImage);
//设置质量
newG.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic;
newG.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;
//置背景色
newG.Clear(Color.White);
//画图
newG.DrawImage(initImage, new System.Drawing.Rectangle(bg_x, bg_y, bg_w, bg_h), new System.Drawing.Rectangle(x, y, ow, oh), System.Drawing.GraphicsUnit.Pixel);
if (filename == "")
{
filename = ofilename;
}
savePath += filename;
var format = ImageFormat.Jpeg;
switch (extand)
{
case "png": format = ImageFormat.Png; break;
case "gif": format = ImageFormat.Gif; break;
}
newImage.Save(savePath, format);
//释放资源
newG.Dispose();
newImage.Dispose();
}
}
catch (Exception ex)
{
AppLog.Write("生成缩略图报错", AppLog.LogMessageType.Error, ex);
this.Dispose();
}
//释放资源
//initImage.Dispose();
//fs.Dispose();
}
/// <summary>
/// 图片缩放,按比例存储缩略图
/// </summary>
/// <param name="savePath">缩略图存放地址</param>
/// <param name="width">缩略图最大宽度</param>
/// <param name="height">缩略图最大高度</param>
/// <param name="filename">重命名,带扩展名</param>
public void ZoomAuto(string savePath, int width, int height,int x,int y, string filename = "", string extand = "jpg")
{
if (fs == null)
return;
//如存放地址不存在,创建地址
if (!Directory.Exists(savePath))
Directory.CreateDirectory(savePath);
System.Drawing.Image newImage;
System.Drawing.Graphics newG;
try
{
if (width > 0 && height > 0)
{
//原始图片写入画布坐标和宽高(用来设置裁减溢出部分)
int ow = width;
int oh = height;
//原始图片画布,设置写入缩略图画布坐标和宽高(用来原始图片整体宽高缩放)
int bg_x = 0;
int bg_y = 0;
int bg_w = width;
int bg_h = height;
//生成新图
//新建一个bmp图片
newImage = new System.Drawing.Bitmap(width, height);
//新建一个画板
newG = System.Drawing.Graphics.FromImage(newImage);
//设置质量
newG.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic;
newG.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;
//置背景色
newG.Clear(Color.White);
//画图
newG.DrawImage(initImage, new System.Drawing.Rectangle(bg_x, bg_y, bg_w, bg_h), new System.Drawing.Rectangle(x, y, ow, oh), System.Drawing.GraphicsUnit.Pixel);
if (filename == "")
{
filename = ofilename;
}
savePath += filename;
var format = ImageFormat.Jpeg;
switch (extand)
{
case "png": format = ImageFormat.Png; break;
case "gif": format = ImageFormat.Gif; break;
}
newImage.Save(savePath, format);
//释放资源
newG.Dispose();
newImage.Dispose();
}
}
catch (Exception ex)
{
AppLog.Write("生成缩略图报错", AppLog.LogMessageType.Error, ex);
this.Dispose();
}
//释放资源
//initImage.Dispose();
//fs.Dispose();
}
}
}
(十八)各种加密
密钥转换类
using System;
using System.Xml;
using Org.BouncyCastle.Asn1.Pkcs;
using Org.BouncyCastle.Asn1.X509;
using Org.BouncyCastle.Crypto.Parameters;
using Org.BouncyCastle.Math;
using Org.BouncyCastle.Pkcs;
using Org.BouncyCastle.Security;
using Org.BouncyCastle.X509;
namespace Test
{
/// <summary>
/// 密钥转换帮助类
/// </summary>
public class RSAKeyConvert
{
/// <summary>
/// RSA私钥格式转换,java->.net
/// </summary>
/// <param name="privateKey">java生成的RSA私钥</param>
/// <returns></returns>
public static string RSAPrivateKeyJava2DotNet(string privateKey)
{
RsaPrivateCrtKeyParameters privateKeyParam = (RsaPrivateCrtKeyParameters)PrivateKeyFactory.CreateKey(Convert.FromBase64String(privateKey));
return string.Format("<RSAKeyValue><Modulus>{0}</Modulus><Exponent>{1}</Exponent><P>{2}</P><Q>{3}</Q><DP>{4}</DP><DQ>{5}</DQ><InverseQ>{6}</InverseQ><D>{7}</D></RSAKeyValue>",
Convert.ToBase64String(privateKeyParam.Modulus.ToByteArrayUnsigned()),
Convert.ToBase64String(privateKeyParam.PublicExponent.ToByteArrayUnsigned()),
Convert.ToBase64String(privateKeyParam.P.ToByteArrayUnsigned()),
Convert.ToBase64String(privateKeyParam.Q.ToByteArrayUnsigned()),
Convert.ToBase64String(privateKeyParam.DP.ToByteArrayUnsigned()),
Convert.ToBase64String(privateKeyParam.DQ.ToByteArrayUnsigned()),
Convert.ToBase64String(privateKeyParam.QInv.ToByteArrayUnsigned()),
Convert.ToBase64String(privateKeyParam.Exponent.ToByteArrayUnsigned()));
}
/// <summary>
/// RSA私钥格式转换,.net->java
/// </summary>
/// <param name="privateKey">.net生成的私钥</param>
/// <returns></returns>
public static string RSAPrivateKeyDotNet2Java(string privateKey)
{
XmlDocument doc = new XmlDocument();
doc.LoadXml(privateKey);
BigInteger m = new BigInteger(1, Convert.FromBase64String(doc.DocumentElement.GetElementsByTagName("Modulus")[0].InnerText));
BigInteger exp = new BigInteger(1, Convert.FromBase64String(doc.DocumentElement.GetElementsByTagName("Exponent")[0].InnerText));
BigInteger d = new BigInteger(1, Convert.FromBase64String(doc.DocumentElement.GetElementsByTagName("D")[0].InnerText));
BigInteger p = new BigInteger(1, Convert.FromBase64String(doc.DocumentElement.GetElementsByTagName("P")[0].InnerText));
BigInteger q = new BigInteger(1, Convert.FromBase64String(doc.DocumentElement.GetElementsByTagName("Q")[0].InnerText));
BigInteger dp = new BigInteger(1, Convert.FromBase64String(doc.DocumentElement.GetElementsByTagName("DP")[0].InnerText));
BigInteger dq = new BigInteger(1, Convert.FromBase64String(doc.DocumentElement.GetElementsByTagName("DQ")[0].InnerText));
BigInteger qinv = new BigInteger(1, Convert.FromBase64String(doc.DocumentElement.GetElementsByTagName("InverseQ")[0].InnerText));
RsaPrivateCrtKeyParameters privateKeyParam = new RsaPrivateCrtKeyParameters(m, exp, d, p, q, dp, dq, qinv);
PrivateKeyInfo privateKeyInfo = PrivateKeyInfoFactory.CreatePrivateKeyInfo(privateKeyParam);
byte[] serializedPrivateBytes = privateKeyInfo.ToAsn1Object().GetEncoded();
return Convert.ToBase64String(serializedPrivateBytes);
}
/// <summary>
/// RSA公钥格式转换,java->.net
/// </summary>
/// <param name="publicKey">java生成的公钥</param>
/// <returns></returns>
public static string RSAPublicKeyJava2DotNet(string publicKey)
{
RsaKeyParameters publicKeyParam = (RsaKeyParameters)PublicKeyFactory.CreateKey(Convert.FromBase64String(publicKey));
return string.Format("<RSAKeyValue><Modulus>{0}</Modulus><Exponent>{1}</Exponent></RSAKeyValue>",
Convert.ToBase64String(publicKeyParam.Modulus.ToByteArrayUnsigned()),
Convert.ToBase64String(publicKeyParam.Exponent.ToByteArrayUnsigned()));
}
/// <summary>
/// RSA公钥格式转换,.net->java
/// </summary>
/// <param name="publicKey">.net生成的公钥</param>
/// <returns></returns>
public static string RSAPublicKeyDotNet2Java(string publicKey)
{
XmlDocument doc = new XmlDocument(); doc.LoadXml(publicKey);
BigInteger m = new BigInteger(1, Convert.FromBase64String(doc.DocumentElement.GetElementsByTagName("Modulus")[0].InnerText));
BigInteger p = new BigInteger(1, Convert.FromBase64String(doc.DocumentElement.GetElementsByTagName("Exponent")[0].InnerText));
RsaKeyParameters pub = new RsaKeyParameters(false, m, p);
SubjectPublicKeyInfo publicKeyInfo = SubjectPublicKeyInfoFactory.CreateSubjectPublicKeyInfo(pub);
byte[] serializedPublicBytes = publicKeyInfo.ToAsn1Object().GetDerEncoded();
return Convert.ToBase64String(serializedPublicBytes);
}
/// <summary>
/// 重写FromXmlString方法(core 2.2以下使用原生的FormXMLstirng会报错)
/// </summary>
/// <param name="xmlString"></param>
/// <returns></returns>
public static RSACryptoServiceProvider FromXmlString(string xmlString)
{
var rsa = new RSACryptoServiceProvider();
RSAParameters parameters = new RSAParameters();
XmlDocument xmlDoc = new XmlDocument();
xmlDoc.LoadXml(xmlString);
if (xmlDoc.DocumentElement.Name.Equals("RSAKeyValue"))
{
foreach (XmlNode node in xmlDoc.DocumentElement.ChildNodes)
{
switch (node.Name)
{
case "Modulus": parameters.Modulus = Convert.FromBase64String(node.InnerText); break;
case "Exponent": parameters.Exponent = Convert.FromBase64String(node.InnerText); break;
case "P": parameters.P = Convert.FromBase64String(node.InnerText); break;
case "Q": parameters.Q = Convert.FromBase64String(node.InnerText); break;
case "DP": parameters.DP = Convert.FromBase64String(node.InnerText); break;
case "DQ": parameters.DQ = Convert.FromBase64String(node.InnerText); break;
case "InverseQ": parameters.InverseQ = Convert.FromBase64String(node.InnerText); break;
case "D": parameters.D = Convert.FromBase64String(node.InnerText); break;
}
}
}
else
{
throw new Exception("Invalid XML RSA key.");
}
rsa.ImportParameters(parameters);
return rsa;
}
}
}
RSA对称加密帮助类
using System;
using System.Collections.Generic;
using System.Security.Cryptography;
using System.Security.Cryptography.X509Certificates;
using System.Text;
using System.Linq;
namespace Test
{
/// <summary>
/// 对称加密帮助类
/// </summary>
public class ResHelper
{
/// <summary>
/// 加密
/// </summary>
/// <param name="data">需加密字符串或文件byte</param>
/// <param name="publicKey">公钥</param>
/// <returns></returns>
public static byte[] EncryptData(byte[] data,string publicKey)
{
RSACryptoServiceProvider rsa = new RSACryptoServiceProvider(1024);
//将公钥导入到RSA对象中,准备加密;
rsa.FromXmlString(publicKey);
//对数据data进行加密,并返回加密结果;
//第二个参数用来选择Padding的格式
byte[] buffer = rsa.Encrypt(data, false);
return buffer;
}
/// <summary>
/// 解密
/// </summary>
/// <param name="data">需解密byte</param>
/// <param name="privateKey">私钥</param>
/// <returns></returns>
public static byte[] DecryptData(byte[] data, string privateKey)
{
RSACryptoServiceProvider rsa = new RSACryptoServiceProvider(1024);
//将私钥导入RSA中,准备解密;
rsa.FromXmlString(privateKey);
//对数据进行解密,并返回解密结果;
return rsa.Decrypt(data, false);
}
/// <summary>
/// 私钥签名
/// </summary>
/// <param name="data"></param>
/// <param name="cer"></param>
/// <returns></returns>
public static byte[] RsaSignature(byte[] data, X509Certificate2 cer) {
SHA256 sha256 = new SHA256CryptoServiceProvider();
byte[] hashbytes = sha256.ComputeHash(data); //对要签名的数据进行哈希
RSAPKCS1SignatureFormatter signe = new RSAPKCS1SignatureFormatter();
signe.SetKey(cer.PrivateKey); //设置签名用到的私钥
signe.SetHashAlgorithm("SHA256"); //设置签名算法
return signe.CreateSignature(hashbytes);
}
/// <summary>
/// 验证是否有改动
/// </summary>
/// <param name="data"></param>
/// <param name="sign"></param>
/// <param name="cer"></param>
/// <returns></returns>
public static bool RsaVerifyData(byte[] data,byte[] sign, X509Certificate2 cer) {
RSACryptoServiceProvider oRSA4 = new RSACryptoServiceProvider();
oRSA4.FromXmlString(cer.PublicKey.Key.ToXmlString(false));
return oRSA4.VerifyData(data, "SHA256", sign);
}
/// <summary>
/// 生成签名
/// </summary>
/// <param name="sPara"></param>
/// <param name="privateKey"></param>
/// <returns></returns>
public static string BuildRequestKuaiQianSignOline(Dictionary<string, string> sPara,string privateKey)
{
string signMsg = CreateLinkStringOline(sPara);
var netKey = RSAKeyConvert.RSAPrivateKeyJava2DotNet(privateKey); //转换成适用于.net的私钥
string sign = Signature(signMsg, netKey);
return sign;
}
/// <summary>
/// 转换字典
/// </summary>
/// <param name="dicArray"></param>
/// <returns></returns>
public static string CreateLinkStringOline(Dictionary<string, string> dicArray)
{
var vDic = (from objDic in dicArray orderby objDic.Key ascending select objDic); //按各字符的ASCII码从小到大排序
var keys = dicArray.Keys.ToList();
keys = keys.OrderBy(a => a).ToList();
StringBuilder prestr = new StringBuilder();
foreach (var item in keys)
{
prestr.Append(item + "=" + dicArray[item] + "&");
}
//去掉最后字符
int nLen = prestr.Length;
prestr.Remove(nLen - 1, 1);
return prestr.ToString();
}
/// <summary>
/// 生成签名
/// </summary>
/// <param name="str">需签名的数据</param>
/// <param name="privateKey">私钥</param>
/// <param name="encoding">编码格式 默认utf-8</param>
/// <returns>签名后的值</returns>
public static string Signature(string str, string privateKey, string encoding = "utf-8")
{
//SHA256withRSA
//根据需要加签时的哈希算法转化成对应的hash字符节
//byte[] bt = Encoding.GetEncoding("utf-8").GetBytes(str);
byte[] bt = Encoding.GetEncoding(encoding).GetBytes(str);
var sha256 = new SHA256CryptoServiceProvider();
byte[] rgbHash = sha256.ComputeHash(bt);
RSACryptoServiceProvider key = new RSACryptoServiceProvider();
key.FromXmlString(privateKey);
RSAPKCS1SignatureFormatter formatter = new RSAPKCS1SignatureFormatter(key);
formatter.SetHashAlgorithm("SHA256");//此处是你需要加签的hash算法,需要和上边你计算的hash值的算法一致,不然会报错。
byte[] inArray = formatter.CreateSignature(rgbHash);
return Convert.ToBase64String(inArray);
}
/// <summary>
/// AES加密
/// </summary>
/// <param name="str">明文(待加密)</param>
/// <param name="key">密文</param>
/// <returns></returns>
public static string AesEncrypt(string str, string key,string iv)
{
if (string.IsNullOrEmpty(str)) return null;
Byte[] toEncryptArray = Encoding.UTF8.GetBytes(str);
RijndaelManaged rm = new RijndaelManaged
{
Key = Encoding.UTF8.GetBytes(key),
Mode = CipherMode.CBC,
Padding = PaddingMode.PKCS7,
IV = Encoding.UTF8.GetBytes(iv)
};
ICryptoTransform cTransform = rm.CreateEncryptor();
Byte[] resultArray = cTransform.TransformFinalBlock(toEncryptArray, 0, toEncryptArray.Length);
return Convert.ToBase64String(resultArray, 0, resultArray.Length);
}
/// <summary>
/// AES 解密
/// </summary>
/// <param name="str">明文(待解密)</param>
/// <param name="key">密文</param>
/// <returns></returns>
public static string AesDecrypt(string str, string key, string iv)
{
if (string.IsNullOrEmpty(str)) return null;
Byte[] toEncryptArray = Convert.FromBase64String(str);
RijndaelManaged rm = new RijndaelManaged
{
Key = Encoding.UTF8.GetBytes(key),
Mode = CipherMode.CBC,
Padding = PaddingMode.PKCS7,
IV= Encoding.UTF8.GetBytes(iv),
};
ICryptoTransform cTransform = rm.CreateDecryptor();
Byte[] resultArray = cTransform.TransformFinalBlock(toEncryptArray, 0, toEncryptArray.Length);
return Encoding.UTF8.GetString(resultArray);
}
}
}
(十九)枚举操作
// 枚举
public enum enumStudent
{
[Description("性别")]
sex = 0,
[Description("年龄")]
age = 1,
}
// 获取描述
public static string GetDescriptionByEnum(this Enum enumValue)
{
string value = enumValue.ToString();
System.Reflection.FieldInfo field = enumValue.GetType().GetField(value);
object[] objs = field.GetCustomAttributes(typeof(DescriptionAttribute), false); //获取描述属性
if (objs.Length == 0) //当描述属性没有时,直接返回名称
return value;
DescriptionAttribute descriptionAttribute = (DescriptionAttribute)objs[0];
return descriptionAttribute.Description;
}
// 调用示例
GetDescriptionByEnum(enumStudent.age) → 年龄
//通过描述获取对应的枚举
public T GetEnumByDescription<T>(string description) where T : Enum
{
System.Reflection.FieldInfo[] fields = typeof(T).GetFields();
foreach(System.Reflection.FieldInfo field in fields)
{
object[] objs = field.GetCustomAttributes(typeof(DescriptionAttribute), false); //获取描述属性
if (objs.Length > 0 && (objs[0] as DescriptionAttribute).Description == description)
{
return (T)field.GetValue(null);
}
}
throw new ArgumentException(string.Format("{0} 未能找到对应的枚举.", description), "Description");
}
// 调用示例
GetEnumByDescription<enumStudent>("性别").ToString() → sex
(二十)startup获取依赖方法
services.AddHttpClient<TestClass>();
var a = services.BuildServiceProvider().GetService<TestClass>();
a.TestRun();
(二十一)各类请求
HttpClient _client;//依赖注入
//Get
_client.DefaultRequestHeaders.Add("Authorization", GetAccessTokenHeaderByCache());//添加Header
var response = await _client.GetAsync(url);
response.EnsureSuccessStatusCode();
json = await response.Content.ReadAsStringAsync();//获取字符串
stream = await response.Content.ReadAsStreamAsync();//获取文件流
_client.DefaultRequestHeaders.Remove("Authorization");//删除Header
//post
var postData = new StringContent(jsonData, Encoding.UTF8, "application/json");
HttpContent str = new StringContent(jsonData);
str.Headers.Remove("Content-Type");
str.Headers.Add("Content-Type", "application/json");
var response = await _client.PostAsync(_appDomian+url, str);
response.EnsureSuccessStatusCode();
json = await response.Content.ReadAsStringAsync();
//x-www-form-urlencoded
var content = new StringContent("image=" + HttpUtility.UrlEncode(base64Img), Encoding.UTF8, "application/x-www-form-urlencoded");
var response = await _client.PostAsync(url, content);
response.EnsureSuccessStatusCode();
var content = await response.Content.ReadAsStringAsync();
//form
MultipartFormDataContent multiContent = new MultipartFormDataContent()
{
{ new StringContent(idCard), "idCard"},//证件号
{ new ByteArrayContent(System.IO.File.ReadAllBytes(filePath)), "file", Path.GetFileName(filePath)},//文件流(支持文件格式docx和pdf)
};
var response = await _client.PostAsync(url, multiContent);
response.EnsureSuccessStatusCode();
json = await response.Content.ReadAsStringAsync();
//提交文件流
var response = await _client.PostAsync(url, new ByteArrayContent(System.IO.File.ReadAllBytes(filePath)));
response.EnsureSuccessStatusCode();
json = await response.Content.ReadAsStringAsync();
//当接口文档写了用appkey和sercet组合生成Authorization时,用”:“拼接,用 System.Text.Encoding.UTF8.GetBytes(id+":"+secret);
//转成byte,用string base64str = Convert.ToBase64String(bufOfUTF);转成base64string再赋值到hearder上
(二十二) decimal不四舍五入
((int)(d * 100) / 100.0).ToString(); //注意,分母的100必须是带小数点的
(二十三)高八位低八位Int相互转换
/// <summary>
/// 获取数字高八位第八位
/// </summary>
/// <param name="CRC">指纹模块限制只能为1-0xFFF(4095)</param>
/// <param name="CRCL"></param>
/// <param name="CRLH"></param>
/// <returns></returns>
private bool GetHL8(int CRC,out int CRCL,out int CRLH) {
CRCL = 0;
CRLH = 0;
if (CRC >= 1 && CRC <= 0XFFF) {
string S = Convert.ToString(CRC, 16);//转换为16进制字符串0x6398
int CrcL = CRC % 256; //低8位,取余
CRCL = CRC & (0XFF); //取低8位,152
int CrcH = CRC / 256; //高8位,除256
CRLH = (CRC >> 8) & 0XFF;
return true;
}
return false;
}
/// <summary>
/// 高八位第八位转换成int
/// </summary>
/// <param name="l">低八位</param>
/// <param name="h">高八位</param>
/// <returns></returns>
public static int GetHL8Int(string l, string h)
{
return GetHL8Int(Convert.ToInt32(l, 16), Convert.ToInt32(h, 16));
}
/// <summary>
/// 高八位第八位转换成int
/// </summary>
/// <param name="l">低八位</param>
/// <param name="h">高八位</param>
/// <returns></returns>
public static int GetHL8Int(int l, int h)
{
return l + h * 256;
}
(二十四)把字符数组按ASCII排序
List<string> lstParam = new List<string>();
lstParam.Add(_tencentAppId);
lstParam.Add(orderNo);
lstParam.Add(userId.ToString());
lstParam.Add(h5faceId);
lstParam.Add("1.0.0");
nonce = CreateRandomStr(32);
lstParam.Add(nonce);
lstParam.Add(GetNonceTicketAsync(userId).Result.tickets[0].value);
String[] arrayParam = lstParam.ToArray();
Array.Sort(arrayParam, String.CompareOrdinal);
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· 阿里巴巴 QwQ-32B真的超越了 DeepSeek R-1吗?
· 【译】Visual Studio 中新的强大生产力特性
· 10年+ .NET Coder 心语 ── 封装的思维:从隐藏、稳定开始理解其本质意义
· 【设计模式】告别冗长if-else语句:使用策略模式优化代码结构