using System;
using System.Collections.Generic;
using System.Text;
using System.Windows.Forms;
using System.Runtime.InteropServices;
using System.Drawing;
using System.Collections;
using System.IO;
using System.Drawing.Imaging;
using System.IO.Compression;
using System.Diagnostics;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Formatters.Binary;
using Newtonsoft.Json;
namespace Util
{
#region EnumStringAttribute
[AttributeUsage(AttributeTargets.Field, AllowMultiple = false, Inherited = false)]
public class EnumStringAttribute : System.Attribute
{
public EnumStringAttribute(string str)
{
this.enumStr = str;
}
public string GetEnumString()
{
return this.enumStr;
}
private string enumStr;
}
#endregion
public class Util
{
/// <summary>
/// 得到可执行程序所在的目录,最后具有分隔符“\\”。
/// </summary>
/// <returns></returns>
public static string GetApplicationPath()
{
return AppDomain.CurrentDomain.BaseDirectory;
}
/// <summary>
/// 填充并显示窗体到Panel中
/// </summary>
/// <param name="panel"></param>
/// <param name="frm"></param>
public static void fillShowFrmToPanel(Panel panel, Form frm)
{
if (panel.Controls.Contains(frm))
{
return;
}
panel.Controls.Clear();
frm.TopLevel = false;
panel.Controls.Add(frm);
frm.FormBorderStyle = FormBorderStyle.None;
frm.Dock = DockStyle.Fill;
frm.Show();
}
/// <summary>
/// 将文件名中的非法字符替换为'_',得到有效的文件名
/// </summary>
/// <param name="filename"></param>
/// <returns></returns>
public static string GetValidFileName(string filename)
{
string newname = filename;
newname = newname.Replace('/', '_');
newname = newname.Replace('\\', '_');
newname = newname.Replace(':', '_');
newname = newname.Replace('*', '_');
newname = newname.Replace('?', '_');
newname = newname.Replace('"', '_');
newname = newname.Replace('<', '_');
newname = newname.Replace('>', '_');
newname = newname.Replace('|', '_');
newname = newname.Replace((char)0xA, ' ');
return newname;
}
/// <summary>
/// 将字符串转化为整数
/// </summary>
/// <param name="val"></param>
/// <param name="defVal"></param>
/// <returns></returns>
public static int ToInt(string val, int defVal)
{
if (string.IsNullOrEmpty(val))
return defVal;
try
{
if (val.StartsWith("0x") || val.StartsWith("0X"))
{
return int.Parse(val.Substring(2, val.Length - 2),
System.Globalization.NumberStyles.HexNumber);
}
else
{
return int.Parse(val);
}
}
catch (Exception e)
{
Console.WriteLine("数据转换格式错误:val: {0} {1}", val, e.Message);
return defVal;
}
}
/// <summary>
/// 将字符串转换为长整数。
/// </summary>
/// <param name="val"></param>
/// <param name="defVal"></param>
/// <returns></returns>
public static long ToLong(string val, long defVal)
{
if (string.IsNullOrEmpty(val))
return defVal;
try
{
if (val.StartsWith("0x") || val.StartsWith("0X"))
{
return long.Parse(val.Substring(2, val.Length - 2),
System.Globalization.NumberStyles.HexNumber);
}
else
{
return long.Parse(val);
}
}
catch (Exception e)
{
Console.WriteLine("数据转换格式错误:val: {0} {1}", val, e.Message);
return defVal;
}
}
/// <summary>
/// 将二进制转化为16进制字符串。
/// </summary>
/// <param name="buf"></param>
/// <returns></returns>
public static string BinaryToString(byte[] buf, int maxLen)
{
if (buf == null)
return "";
int count = Math.Min(buf.Length, maxLen);
bool bOmit = count < buf.Length;
StringBuilder sb = new StringBuilder(count * 2 + 30);
for (int i = 0; i < count; ++i)
{
sb.Append(buf[i].ToString("X2"));
}
if (bOmit)
sb.Append(string.Format(" ... Total {0} Bytes", buf.Length));
return sb.ToString();
}
/// <summary>
/// 将二进制转化为16进制字符串。
/// </summary>
/// <param name="buf"></param>
/// <param name="cntPerRow">每行显示几个字节</param>
/// <returns></returns>
public static string BinaryToStringFormat(byte[] buf, int cntPerRow)
{
if (buf == null)
return "";
StringBuilder sb = new StringBuilder(buf.Length * 2);
int cnt = 0;
int cntall = 0;
foreach (byte b in buf)
{
cnt++;
cntall++;
if (cnt == 1)
{
sb.Append((cntall - 1).ToString("d4")).Append(" : ");
}
sb.Append(b.ToString("X2")).Append(" ");
if (cnt >= cntPerRow)
{
sb.AppendLine();
cnt = 0;
}
}
return sb.ToString();
}
/// <summary>
/// 将字符串转化为二进制数据数组
/// </summary>
/// <param name="str"></param>
/// <returns></returns>
public static byte[] BinaryFromString(string str)
{
if (string.IsNullOrEmpty(str))
return new byte[0];
str = str.Trim();
int len = str.Length / 2;
byte[] buf = new byte[len + (str.Length % 2)];
for (int i = 0; i < len; ++i)
{
buf[i] = byte.Parse(str.Substring(i * 2, 2),
System.Globalization.NumberStyles.HexNumber);
}
if ((str.Length % 2) > 0)
{
// 最后一个字符
buf[buf.Length - 1] = byte.Parse(str.Substring(str.Length - 1, 1),
System.Globalization.NumberStyles.HexNumber);
}
return buf;
}
/// <summary>
/// byte数组格式化为十六进制的字符串
/// </summary>
/// <param name="buffer"></param>
/// <param name="len">长度</param>
/// <param name="spliter">分割符</param>
/// <returns></returns>
public static string BufferFormat(byte[] buffer, int len, char spliter)
{
StringBuilder sb = new StringBuilder("");
if (buffer == null)
return sb.ToString();
for (int i = 0; i < len; ++i)
{
sb.Append(buffer[i].ToString("X2")).Append(spliter);
}
return sb.ToString();
}
public static uint ColorToInt(Color color)
{
return (uint)(((uint)color.B << 16) | (ushort)(((ushort)color.G << 8) | color.R));
}
public static Color IntToColor(int color)
{
int r = 0xFF & color;
int g = 0xFF00 & color;
g >>= 8;
int b = 0xFF0000 & color;
b >>= 16;
return Color.FromArgb(r, g, b);
}
#region DllImport 把窗体导出为图片使用
[DllImport("user32.dll")]
public static extern IntPtr GetWindowRect(IntPtr hWnd, ref Rectangle rect);
[DllImport("gdi32.dll")]
public static extern IntPtr CreateCompatibleDC(IntPtr hdc);
[DllImport("gdi32.dll")]
public static extern IntPtr CreateCompatibleBitmap(IntPtr hdc, int nWidth, int nHeight);
[DllImport("gdi32.dll")]
public static extern IntPtr SelectObject(IntPtr hdc, IntPtr hgdiobj);
[DllImport("gdi32.dll")]
public static extern int DeleteDC(IntPtr hdc);
[DllImport("gdi32.dll")]
public static extern bool BitBlt(
IntPtr hdcDest, // 目的 DC的句柄
int nXDest,
int nYDest,
int nWidth,
int nHeight,
IntPtr hdcSrc, // 源DC的句柄
int nXSrc,
int nYSrc,
System.Int32 dwRop // 光栅的处置数值
);
[DllImport("user32.dll")]
public static extern bool PrintWindow(IntPtr hwnd, IntPtr hdcBlt, UInt32 nFlags);
[DllImport("user32.dll")]
public static extern IntPtr GetWindowDC(IntPtr hwnd);
#endregion
/// <summary>
/// 根据窗口句柄,把窗口显示导出图片(.bmp)
/// </summary>
/// <param name="hWnd"></param>
/// <returns></returns>
public static Bitmap GetWindowCapture(IntPtr hWnd)
{
IntPtr hscrdc = GetWindowDC(hWnd);
Rectangle windowRect = new Rectangle();
GetWindowRect(hWnd, ref windowRect);
int width = windowRect.Right - windowRect.Left;
int height = windowRect.Bottom - windowRect.Top;
IntPtr hbitmap = CreateCompatibleBitmap(hscrdc, width, height);
IntPtr hmemdc = CreateCompatibleDC(hscrdc);
SelectObject(hmemdc, hbitmap);
PrintWindow(hWnd, hmemdc, 0);
Bitmap bmp = Bitmap.FromHbitmap(hbitmap);
DeleteDC(hscrdc);//删除用过的对象
DeleteDC(hmemdc);//删除用过的对象
return bmp;
}
public static string BufferFormatSimple(byte[] buffer)
{
return Util.BufferFormat(buffer, buffer.Length, ' ');
}
static Dictionary<string, List<string>> typeHash =
new Dictionary<string, List<string>>();
/// <summary>
/// 得到与枚举类型值相关联的字符串
/// </summary>
/// <param name="type"></param>
/// <returns></returns>
public static List<string> GetEnumString(Type type)
{
if (typeHash.ContainsKey(type.ToString()))
{
return typeHash[type.ToString()];
}
else
{
List<string> list = new List<string>();
System.Reflection.MemberInfo[] mis = type.GetMembers();
foreach (System.Reflection.MemberInfo mi in mis)
{
Attribute[] attrs = System.Attribute.GetCustomAttributes(mi);
foreach (Attribute at in attrs)
{
if (at is EnumStringAttribute)
{
list.Add(((EnumStringAttribute)at).GetEnumString());
}
}
}
typeHash[type.ToString()] = list;
return list;
}
}
static Hashtable enumValueHash = new Hashtable();
/// <summary>
/// 由枚举类型及枚举显示字符串得到枚举数值。
/// 如 由 SexType "男" 得到 (int)SexType.Male
/// </summary>
/// <param name="enumType"></param>
/// <param name="enumDisStr"></param>
/// <returns></returns>
public static int GetEnumValue(Type enumType, string enumDisStr)
{
string key = enumType.ToString() + enumDisStr;
if (enumValueHash.Contains(key))
{
return (int)enumValueHash[key];
}
else
{
int ret = -1;
System.Reflection.MemberInfo[] mis = enumType.GetMembers();
foreach (System.Reflection.MemberInfo mi in mis)
{
Attribute[] attrs = System.Attribute.GetCustomAttributes(mi);
foreach (Attribute at in attrs)
{
if (at is EnumStringAttribute)
{
EnumStringAttribute esr = (EnumStringAttribute)at;
if (esr.GetEnumString() == enumDisStr)
{
ret = (int)System.Enum.Parse(enumType, mi.Name);
break;
}
}
}
if (ret != -1)
break;
}
enumValueHash[key] = ret;
return ret;
}
}
static Hashtable enumStringHash = new Hashtable();
/// <summary>
/// 有枚举类型及枚举值得到显示字符串。
/// 如 由 SexType (int)SexType.Male 得到 "男"
/// </summary>
/// <param name="enumType"></param>
/// <param name="enumVal"></param>
/// <returns></returns>
public static string GetEnumDisString(Type enumType, int enumVal)
{
string key = enumType.ToString() + enumVal.ToString();
if (enumStringHash.Contains(key))
{
return (string)enumStringHash[key];
}
else
{
string ret = "";
System.Reflection.MemberInfo[] mis = enumType.GetMembers();
foreach (System.Reflection.MemberInfo mi in mis)
{
Attribute[] attrs = System.Attribute.GetCustomAttributes(mi);
foreach (Attribute at in attrs)
{
if (at is EnumStringAttribute)
{
EnumStringAttribute esr = (EnumStringAttribute)at;
//object obj = System.Enum.Parse(enumType, mi.Name);
if ((int)System.Enum.Parse(enumType, mi.Name) == enumVal)
{
ret = esr.GetEnumString();
break;
}
}
}
if (ret != "")
break;
}
enumStringHash[key] = ret;
return ret;
}
}
private static ImageCodecInfo GetEncoderInfo(string mimeType)
{
// Get image codecs for all image formats
ImageCodecInfo[] codecs = ImageCodecInfo.GetImageEncoders();
// Find the correct image codec
for (int i = 0; i < codecs.Length; i++)
if (codecs[i].MimeType == mimeType)
return codecs[i];
return null;
}
public static byte[] ConvertToJpgBuff(Image bmp, long quality)
{
// Encoder parameter for image quality
EncoderParameter qualityParam = new EncoderParameter(System.Drawing.Imaging.Encoder.Quality, quality);
// JPEG image codec
ImageCodecInfo jpegCodec = GetEncoderInfo("image/jpeg");
EncoderParameters encoderParams = new EncoderParameters(1);
encoderParams.Param[0] = qualityParam;
MemoryStream msJpg = new MemoryStream();
bmp.Save(msJpg, jpegCodec, encoderParams);
bmp.Dispose();
return msJpg.ToArray();
}
/// <summary>
/// Convert Image to Byte[]
/// </summary>
/// <param name="image"></param>
/// <returns></returns>
public static byte[] ImageToBytes(Image image)
{
ImageFormat format = image.RawFormat;
using (MemoryStream ms = new MemoryStream())
{
if (format.Equals(ImageFormat.Jpeg))
{
image.Save(ms, ImageFormat.Jpeg);
}
else if (format.Equals(ImageFormat.Png))
{
image.Save(ms, ImageFormat.Png);
}
else if (format.Equals(ImageFormat.Bmp))
{
image.Save(ms, ImageFormat.Bmp);
}
else if (format.Equals(ImageFormat.Gif))
{
image.Save(ms, ImageFormat.Gif);
}
else if (format.Equals(ImageFormat.Icon))
{
image.Save(ms, ImageFormat.Icon);
}
else
image.Save(ms, ImageFormat.Jpeg);
byte[] buffer = new byte[ms.Length];
//Image.Save()会改变MemoryStream的Position,需要重新Seek到Begin
ms.Seek(0, SeekOrigin.Begin);
ms.Read(buffer, 0, buffer.Length);
return buffer;
}
}
/// <summary>
/// Convert Byte[] to Image
/// </summary>
/// <param name="buffer"></param>
/// <returns></returns>
public static Image BytesToImage(byte[] buffer)
{
MemoryStream ms = new MemoryStream(buffer);
Image image = System.Drawing.Image.FromStream(ms);
return image;
}
/// <summary>
/// Convert Byte[] to a picture and Store it in file
/// </summary>
/// <param name="fileName"></param>
/// <param name="buffer"></param>
/// <returns></returns>
public static string CreateImageFromBytes(string fileName, byte[] buffer)
{
string file = fileName;
Image image = BytesToImage(buffer);
ImageFormat format = image.RawFormat;
if (format.Equals(ImageFormat.Jpeg))
{
file += ".jpeg";
}
else if (format.Equals(ImageFormat.Png))
{
file += ".png";
}
else if (format.Equals(ImageFormat.Bmp))
{
file += ".bmp";
}
else if (format.Equals(ImageFormat.Gif))
{
file += ".gif";
}
else if (format.Equals(ImageFormat.Icon))
{
file += ".icon";
}
System.IO.FileInfo info = new System.IO.FileInfo(file);
System.IO.Directory.CreateDirectory(info.Directory.FullName);
File.WriteAllBytes(file, buffer);
return file;
}
public static System.DateTime ConvertIntDateTime(long d)
{
System.DateTime time = System.DateTime.MinValue;
System.DateTime startTime = TimeZone.CurrentTimeZone.ToLocalTime(new System.DateTime(1970, 1, 1));
time = startTime.AddMilliseconds(d);
return time;
}
public static long ConvertDateTimeInt(System.DateTime time)
{
//double intResult = 0;
System.DateTime startTime = TimeZone.CurrentTimeZone.ToLocalTime(new System.DateTime(1970, 1, 1, 0, 0, 0, 0));
long t = (time.Ticks - startTime.Ticks) / 10000; //除10000调整为13位
return t;
}
/// <summary>
/// 压缩缓冲区
/// </summary>
/// <param name="inBuff">输入待压缩缓冲区</param>
/// <param name="outBuff">输出压缩后缓冲区</param>
/// <returns></returns>
public static Boolean CompressBuffer(byte[] inBuff, ref byte[] outBuff)
{
Boolean bLess = false;
using (MemoryStream destination = new MemoryStream())
{
using (GZipStream output = new GZipStream(destination, CompressionMode.Compress))
{
output.Write(inBuff, 0, inBuff.Length);
}
destination.Flush();
outBuff = destination.ToArray();
bLess = (outBuff.Length < inBuff.Length);
if (!bLess) outBuff = inBuff;
}
return bLess;
}
/// <summary>
/// 解压缩缓冲区
/// </summary>
/// <param name="inBuff">待解压缓冲区</param>
/// <param name="outBuff">解压后缓冲区</param>
/// <returns></returns>
public static Boolean DecompressBuffer(byte[] inBuff, ref byte[] outBuff)
{
Stream source = new MemoryStream(inBuff);
using (MemoryStream destination = new MemoryStream())
{
using (GZipStream input = new GZipStream(source, CompressionMode.Decompress, true))
{
byte[] bytes = new byte[4096];
int n;
while ((n = input.Read(bytes, 0, bytes.Length)) != 0)
{
destination.Write(bytes, 0, n);
}
}
destination.Flush();
destination.Position = 0;
outBuff = destination.ToArray();
}
return true;
}
/// <summary>
/// 从指定目录获取指定扩展名的文件
/// </summary>
/// <param name="path"></param>
/// <param name="extNameArr"></param>
/// <returns></returns>
public static List<FileInfo> GetDirFiles(string path, params string[] extNameArr)
{
List<FileInfo> lst = new List<FileInfo>();
try
{
string[] dir = Directory.GetDirectories(path); //文件夹列表
DirectoryInfo fdir = new DirectoryInfo(path);
FileInfo[] file = fdir.GetFiles();
if (file.Length != 0 || dir.Length != 0) //当前目录文件或文件夹不为空
{
foreach (FileInfo f in file) //显示当前目录所有文件
{
foreach(string extName in extNameArr)
{
if (extName.ToLower().IndexOf(f.Extension.ToLower()) >= 0)
{
lst.Add(f);
break;
}
}
}
foreach (string d in dir)
{
GetDirFiles(d, extNameArr);//递归
}
}
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
return lst;
}
public static int DBM2Int(string dbm)
{
if (string.IsNullOrEmpty(dbm) || dbm.Length != 3)
{
Debug.Assert(false, "节点DBM不能为空,且长度必须为3," + dbm);
}
int id = 0;
char[] arr = dbm.ToCharArray();
for (int i = 0; i < arr.Length; i++)
{
id <<= 8;
id |= (byte)arr[i];
}
return id;
}
public static string Int2DBM(int id)
{
char[] arr = new char[3];
for (int i = 2; i >= 0; i--)
{
arr[i] = (char)(id & 0xFF);
id >>= 8;
}
return new string(arr);
}
#region 将类和结构序列化和反序列化的方法
/// <summary>
/// 序列化(把类和结构序列化)
/// </summary>
/// <param name="msg">结构信息</param>
/// <returns></returns>
//public static byte[] Serialize(object obj)
//{
// try
// {
// string json = JsonConvert.SerializeObject(obj);
// byte[] buffer = Encoding.UTF8.GetBytes(json);
// return buffer;
// }
// catch (Exception e)
// {
// Console.WriteLine(e.Message);
// //OutPutLog.WriteLog(LogLevel.Error, "Util.Serialize()错误 " + e.Message, LogObjType.Util.ToString());
// }
// return null;
//}
public static byte[] Serialize(object obj)
{
try
{
IFormatter inFormatter = new BinaryFormatter();
MemoryStream stm = new MemoryStream();
inFormatter.Serialize(stm, obj);
byte[] buffer = stm.ToArray();
stm.Close();
stm.Dispose();
return buffer;
}
catch (Exception e)
{
Console.WriteLine(e.Message);
//OutPutLog.WriteLog(LogLevel.Error, "Util.Serialize()错误 " + e.Message, LogObjType.Util.ToString());
}
return null;
}
/// <summary>
/// 反序列化(类和结构的反序列化)
/// </summary>
/// <param name="buffer">串行数据</param>
/// <returns></returns>
//public static object Deserialize(byte[] buffer)
//{
// try
// {
// string json = Encoding.UTF8.GetString(buffer);
// return JsonConvert.DeserializeObject(json) ?? null;
// }
// catch (Exception e)
// {
// Console.WriteLine(e.Message);
// //OutPutLog.WriteLog(LogLevel.Error, "Util.Deserialize() " + e.Message, LogObjType.Util.ToString());
// }
// return null;
//}
public static object Deserialize(byte[] buffer)
{
try
{
MemoryStream stream = new MemoryStream(buffer);
BinaryFormatter outFormatter = new BinaryFormatter();
object obj = outFormatter.Deserialize(stream);
stream.Close();
stream.Dispose();
return obj;
}
catch (Exception e)
{
Console.WriteLine(e.Message);
//OutPutLog.WriteLog(LogLevel.Error, "Util.Deserialize() " + e.Message, LogObjType.Util.ToString());
}
return null;
}
#endregion
}
}
转换.net8.0