using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading;
namespace HPSocketCS.Extended
{
///
/// 程序运行状态
///
public enum AppState
{
///
/// 启动中...
///
Starting=0,
///
/// 已启动
///
Started=1,
///
/// 停止中...
///
Stoping=2,
///
/// 已停止
///
Stoped=3,
///
/// 错误
///
Error=4
}
///
/// 数据类型
///
public enum DataType
{
///
/// 空数据
///
None=0,
///
/// 数组
///
Array=1,
///
/// 集合
///
List=2,
///
/// 文本信息
///
Text=3,
///
/// 序列化数据
///
Serialization=4,
///
/// 文件
///
File=5,
///
/// 显示窗体
///
ShowForm=6,
///
/// 推送消息
///
PushMessage=7,
///
/// 数据库信息处理
///
SQLHelper=8,
}
///
/// 文件传输请求类型
///
public enum FileRequestType
{
///
/// 上传
///
Upload=0,
///
/// 下载
///
Download=1
}
///
/// 通信命令
///
public enum TransferRequestCommand
{
///
/// 测试命令
///
TestCommand=-1,
///
/// 空命令
///
EmptyCommand=0,
///
/// 重要信息
///
VitalInfo=1,
///
/// 重要控制
///
VitalControl = 2,
///
/// 返回结果
///
VitalControlOK=3,
///
/// 文件传输
///
FileTransfer=1000,
///
/// 发送信息
///
Message = 1001,
///
/// 打开文件传输
///
OpenFileTransfer = 1002,
///
/// 关闭文件传输
///
CloseFileTransfer = 1003,
///
/// 上传用户头像
///
UploadAvatar = 1004,
///
/// 下载用户头像
///
DownloadAvatar = 1005,
///
/// 上传文件
///
UploadFile = 1006,
///
/// 下载文件
///
DownloadFile = 1007,
///
/// 获取文件信息
///
GetFileInfo = 1008,
///
/// 获取相片备份路径
///
GetbackupPath = 1009,
///
/// 获取相片保存路径
///
GetSavePath = 1010,
///
/// 上传客人头像
///
UploadCustomersAvatar = 1011,
///
/// 下载客人头像
///
DownloadCustomersAvatar = 1012,
///
/// 获取服务器软件信息,1.服务器ID 一搬为Lock短ID 2.类型 是总服务器还是分店服务器 3.软件业务类型 4.功能类型 5.服务器版本号
///
GetServerSoftwareInfo = 1013,
///
/// 获取数据库连接字符串
///
GetDataConne = 1014,
///
/// 获取相片保存路径集合 用于客户端读取订单相片
///
GetSavePhotoPathList = 1015,
///
/// 获取服务器时间 带有服务器版本号 用于检查客户端是否需要更新
///
ServerDateTime = 1016,
///
/// 删除文件
///
DeleteFile = 1017,
///
/// 生成缩略图
///
GenerateThumbnails = 1018,
///
/// 导入相片请求
///
ImportPhotos = 1019,
///
/// 选片请求
///
SelectPhotos = 1020,
///
/// 查看相片请求
///
LookPhotos = 1021,
///
/// 更新订单请求
///
UpdateOrder = 1022,
///
/// 获取最新客户端皮肤图片
///
GetUpdateClientSkinImage = 1023,
///
/// 删除原始相片
///
DeleteOriginalPhoto = 1024,
///
/// 删除备份相片
///
DeleteBackupPhoto = 1025,
///
/// 获取客户端列表
///
GetClientList = 1026,
///
/// 刷新客户连接
///
RefreshClientList = 1027,
///
/// 获取数据
///
GetBigData = 1028,
///
/// 获取文件列表
///
GeTFileList = 1029,
///
/// 获取目录列表
///
GetDirectoryList = 1030,
///
/// 删除目录
///
DeleteDirectory = 1031,
///
/// 获取备份记录
///
GetBackupRecords=1032,
///
/// 获取总店数据库备份记录
///
GetMainShopBackupRecords=1033,
///
/// 获取总店测试信息
///
MainStoreTestInfo=1034,
///
/// SQL数据库操作
///
SQLHelperData=1035,
///
/// 序例化数据传输
///
SerializationData=1036,
///
/// 安装数据库
///
InstallationDatabase=1037,
///
/// 升级数据库
///
UpgradeDatabase = 1038,
///
/// 刷新云服务器数据
///
RefreshCloudServerData=1039,
///
/// 云登录
///
CloudLoginIP=1040,
///
/// 提效软件信息
///
SubmitSoftwareInfo=1041,
///
/// 获取总店服务器软件信息
///
GetMainStoreServerSoftwareInfo = 1042,
///
/// 备份数据库
///
BackupDatabase=1043,
///
/// 客户端在线连接
///
ClientOnlineConnection=1044,
}
///
/// SQLHelper请求类型
///
public enum SQLHelperRequestType
{
///
/// 执行查询语句,返回DataSet
///
QueryReturnDataSet= 0,
///
/// 执行查询,并返回查询所返回的结果集中第一行的第一列。忽略其他列或行。
///
ExecuteScalar=1,
///
/// 对连接执行 Transact-SQL 语句并返回受影响的行数。
///
ExecuteNonQuery=2,
///
/// 执行存储过程
///
RunProcedure=3,
///
/// 执行事务
///
ExecuteSqlTran=4,
///
/// 检查数据库连接 是否能正常连接数据
///
ExistsSqlConn=5,
}
public delegate void DelegateExecuteThreadStart(ReturnResultObject argumentResult);
public class CommonLibrary
{
public CommonLibrary() {
}
///
/// WebForm和WinForm通用的取当前根目录的方法
///
public static string BasePath
{
get
{
System.Diagnostics.Process p = System.Diagnostics.Process.GetCurrentProcess();
//WebDev.WebServer visual studio web server
//xxx.vhost Winform
//w3wp IIS7
//aspnet_wp IIS6
string processName = p.ProcessName.ToLower();
string retPath = System.Windows.Forms.Application.StartupPath;
if (processName == "aspnet_wp" || processName == "w3wp" || processName == "webdev.webserver" || processName == "iisexpress")
{
if (System.Web.HttpContext.Current != null)
retPath = System.Web.HttpContext.Current.Server.MapPath("~/").TrimEnd(new char[] { '\\' });
else //当控件在定时器的触发程序中使用时就为空
{
retPath = System.AppDomain.CurrentDomain.BaseDirectory.TrimEnd(new char[] { '\\' });
}
}
return retPath;
}
}
///
/// 获取完整路径 只能为文件夹目录路径 检查路径结尾是否存在 “\”符号 如果不存在添加上
///
///
///
public static string GetFullDirectoryPath(string directoryPath)
{
if (directoryPath.LastIndexOf("\\") != directoryPath.Length - 1)
{
directoryPath = directoryPath + "\\";
}
return directoryPath;
}
///
/// 全局ID
///
///
public static long GenerateId()
{
byte[] buffer = Guid.NewGuid().ToByteArray();
return BitConverter.ToInt64(buffer, 0);
}
static string _ServerVersionNumber = "1.0";
///
/// 服务器版本号
///
public static string ServerVersionNumber
{
get { return CommonLibrary._ServerVersionNumber; }
set { CommonLibrary._ServerVersionNumber = value; }
}
static string _ClientMarkID = "ServerHosts";
///
/// 客户端标识ID
///
public static string ClientMarkID
{
get { return CommonLibrary._ClientMarkID; }
set { CommonLibrary._ClientMarkID = value; }
}
static string _ClientMarkName = "服务器主机";
///
/// 客户端标识名称
///
public static string ClientMarkName
{
get { return CommonLibrary._ClientMarkName; }
set { CommonLibrary._ClientMarkName = value; }
}
static string _LoginUsername = "未知用户";
///
///登录用户名
///
public static string LoginUsername
{
get { return CommonLibrary._LoginUsername; }
set { CommonLibrary._LoginUsername = value; }
}
private static string _HardwareCode = "HardwareCode";
///
/// 硬件码
///
public static string HardwareCode
{
get { return CommonLibrary._HardwareCode; }
set { CommonLibrary._HardwareCode = value; }
}
#region 发送数据时的方法
///
/// 获取发送数据时的头协议结构
///
/// 连接ID
/// 附加数据
/// 要发送的数据类型
/// 请求命令
/// 传输标识符
/// 是否有协议尾信息
///
public static TcpHeadInfo GetProtocolHeader(IntPtr ConnId, IntPtr addedDataPtr, DataType dType, TransferRequestCommand requestCommand, Int64 transportID, bool isTail = false)
{
HPSocketCS.Extended.ClientInfo ci = null;
try
{
// IntPtr.Zero;
// ci 就是accept里传入的附加数据了
if (addedDataPtr != IntPtr.Zero)
{
ci = (HPSocketCS.Extended.ClientInfo)Marshal.PtrToStructure(addedDataPtr, typeof(HPSocketCS.Extended.ClientInfo));
}
}
catch { }
TcpHeadInfo protocolHeader = new TcpHeadInfo();
protocolHeader.ConnId = ConnId.ToInt32();
protocolHeader.Hostname = System.Net.Dns.GetHostName();
protocolHeader.MsgDataType = (int)dType;
protocolHeader.RequestCommand = (int)requestCommand;
protocolHeader.IntactSize = 0;
protocolHeader.ServerNowTime = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
protocolHeader.ClientMarkID = CommonLibrary.ClientMarkID;
protocolHeader.ClientMarkName = CommonLibrary.ClientMarkName;
protocolHeader.ServerVersionNumber = CommonLibrary.ServerVersionNumber;
protocolHeader.LoginUsername = CommonLibrary.LoginUsername;
protocolHeader.HardwareCode = CommonLibrary.HardwareCode;
protocolHeader.TransportEnd = true;
protocolHeader.TransportStart = true;
protocolHeader.TransportID = transportID;
protocolHeader.IsTail = isTail;
if (ci != null)
{
protocolHeader.IPAddress = ci.IpAddress;
protocolHeader.Port = ci.Port;
}
return protocolHeader;
}
///
/// 写日志 调试时使用
///
/// 日志内容
/// 日志文件全路径
public static void WriteLogs(string txt)
{
try
{
string fullPath = BasePath + "\\Logs\\MainLogs\\"+DateTime.Now.ToString("yyyy-MM-dd")+".txt";
if (!System.IO.Directory.Exists(System.IO.Path.GetDirectoryName(fullPath)))
{
System.IO.Directory.CreateDirectory(System.IO.Path.GetDirectoryName(fullPath));
}
using (System.IO.StreamWriter sw = new System.IO.StreamWriter(fullPath, true, Encoding.UTF8))
{
sw.WriteLine("【" + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss ") + "】" + txt);
sw.Flush();
sw.Close();
}
}
catch { }
}
///
/// 自动拆包并加上包头 包尾
///
/// 要拆分的数据包
/// 包头结构
/// 每包的最大大小
/// 返回拆分后的数据包集合
public static System.IO.BufferedStream AutoUnpackingAndAddPkgHeader(byte[] sendPackBytes, TcpHeadInfo pkgHeader, TcpTailInfo pkgTail, int maxPackSize)
{
// WriteLogs("压缩前的长度:" + packBytes.Length);
byte[] packBytes = HPSocketCS.Extended.DataSetSerializerDeserialize.DataCompressionRetBytes(sendPackBytes);
System.IO.MemoryStream retDataMstream = new System.IO.MemoryStream();
System.IO.BufferedStream buffStream = new System.IO.BufferedStream(retDataMstream, Sdk.PacketBufferSize * 2);
try
{
// WriteLogs("压缩后的长度:" + packBytes.Length);
// byte[] tempbytes=HPSocketCS.Extended.DataSetSerializerDeserialize.DataDecompressRetBytes(packBytes);
// string tempstr = Encoding.UTF8.GetString(tempbytes, 0, tempbytes.Length);
// WriteLogs("压缩后解压还原后的信息:"+tempstr);
// List byteList = new List();
pkgHeader.IntactSize = packBytes.Length;
pkgHeader.ServerNowTime = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
// 包头大小
int pkgHeaderSize = Marshal.SizeOf(pkgHeader);
int pkgTailSize = 0;
if (pkgHeader.IsTail)
{
pkgTailSize = Marshal.SizeOf(pkgTail);
}
//附加协议数据包大小
int AppendPakSize = pkgHeaderSize + pkgTailSize;
if (packBytes.Length + AppendPakSize <= maxPackSize)
{
pkgHeader.TransportStart = true;
pkgHeader.TransportEnd = true;
//包头数据
byte[] pkgHeaderBytes = StructureToByte(pkgHeader);
// 组合最终发送的封包 (封包头封包体)
byte[] sendBytes = null;
if (pkgHeader.IsTail)
{
byte[] tailBytes = StructureToByte(pkgTail);
sendBytes = CommonLibrary.GetSendBuffer(pkgHeaderBytes, packBytes, tailBytes);
tailBytes = null;
}
else
{
sendBytes = CommonLibrary.GetSendBuffer(pkgHeaderBytes, packBytes, null);
}
buffStream.Write(sendBytes, 0, sendBytes.Length);
//retDataMstream.Write(sendBytes, 0, sendBytes.Length);
// byteList.Add(sendBytes);
sendBytes = null;
pkgHeaderBytes = null;
}
else
{
//每包大小
int packSize = Convert.ToInt32(maxPackSize - AppendPakSize);
//可拆包数
int packCount = packBytes.Length / packSize;
if (packBytes.Length % packSize > 0)
{
packCount = packCount + 1;
}
for (int i = 0; i < packCount; i++)
{
byte[] tempPackBytes = new byte[packSize];
if (i == 0)
{
pkgHeader.TransportStart = true;
pkgHeader.TransportEnd = false;
}
else
{
pkgHeader.TransportStart = false;
pkgHeader.TransportEnd = false;
}
if (i + 1 == packCount)
{
pkgHeader.TransportEnd = true;
tempPackBytes = new byte[packBytes.Length - packSize * i];
}
Array.Copy(packBytes, i * packSize, tempPackBytes, 0, tempPackBytes.Length);
//包头数据
byte[] pkgHeaderBytes = StructureToByte(pkgHeader);
// 组合最终发送的封包 (封包头封包体)
byte[] sendBytes = null;
if (pkgHeader.IsTail)
{
byte[] tailBytes = StructureToByte(pkgTail);
sendBytes = CommonLibrary.GetSendBuffer(pkgHeaderBytes, tempPackBytes, tailBytes);
tailBytes = null;
}
else
{
sendBytes = CommonLibrary.GetSendBuffer(pkgHeaderBytes, tempPackBytes, null);
}
buffStream.Write(sendBytes, 0, sendBytes.Length);
//retDataMstream.Write(sendBytes, 0, sendBytes.Length);
// byteList.Add(sendBytes);
pkgHeaderBytes = null;
sendBytes = null;
}
}
}
catch
{
}
buffStream.Flush();
buffStream.Position = 0;
retDataMstream.Position = 0;
Array.Clear(packBytes, 0, packBytes.Length);
packBytes = null;
//return byteList;
return buffStream;
}
///
/// 由结构体转换为byte数组
///
public static byte[] StructureToByte(T structure)
{
int size = Marshal.SizeOf(typeof(T));
byte[] buffer = new byte[size];
IntPtr bufferIntPtr = Marshal.AllocHGlobal(size);
try
{
Marshal.StructureToPtr(structure, bufferIntPtr, true);
Marshal.Copy(bufferIntPtr, buffer, 0, size);
}
finally
{
Marshal.FreeHGlobal(bufferIntPtr);
}
return buffer;
}
///
/// 组合最终发送的封包 (封包头+封包体)
///
/// 封包头
/// 封包体
///
public static byte[] GetSendBuffer(byte[] headerBytes, byte[] bodyBytes,byte[] tailBytes)
{
// IntPtr ptr = IntPtr.Zero;
byte[] retBytes = null;
try
{
int bufferSize = headerBytes.Length + bodyBytes.Length;
if (tailBytes != null)
{
bufferSize= bufferSize + tailBytes.Length;
}
retBytes = new byte[bufferSize];
// 拷贝包头到缓冲区首部
Array.Copy(headerBytes, 0, retBytes, 0, headerBytes.Length);
//Marshal.Copy(headerBytes, 0, ptr, headerBytes.Length);
// 拷贝包体到缓冲区剩余部分
Array.Copy(bodyBytes, 0, retBytes, headerBytes.Length, bodyBytes.Length);
if (tailBytes != null)
{
// 拷贝包尾到缓冲区剩余部分
Array.Copy(tailBytes, 0, retBytes, headerBytes.Length + bodyBytes.Length, tailBytes.Length);
}
return retBytes;
}
finally
{
headerBytes = null;
bodyBytes = null;
tailBytes = null;
}
}
#endregion
#region 接收数据时的方法
///
/// 接收数据集合
///
List ReceiveDataList = new List();
///
/// 获取本次通信的收接数据处理对象 如果没有时返回null
///
///
///
public ReceiveData GetReceiveData(TcpHeadInfo tcpInfo)
{
ReceiveData retRData = null;
lock (ReceiveDataList)
{
foreach (ReceiveData rData in ReceiveDataList)
{
if (rData.ReceiveRemoteClientInfo.ConnId == tcpInfo.ConnId && rData.ReceiveRemoteClientInfo.TransportID == tcpInfo.TransportID)
{
retRData = rData;
break;
}
}
return retRData;
}
}
///
/// 添加接收数据处理对象
///
///
public void AddReceiveData(ReceiveData rData)
{
lock (ReceiveDataList)
{
this.ReceiveDataList.Add(rData);
}
}
///
/// 移除接收数据处理对象
///
///
public void RemoveReceiveDataData(ReceiveData rData)
{
try
{
lock (ReceiveDataList)
{
ReceiveDataList.Remove(rData);
}
if (rData != null)
{
rData.Dispose();
// rData.ReceiveDataMstream.Close();
// rData.ReceiveDataMstream.Dispose();
// rData.ReceiveDataMstream = null;
rData = null;
}
}
catch { }
finally
{
System.GC.Collect();
}
}
///
/// 清除所有无效连接资源
///
///
public void ClearAllInvalidResource()
{
lock (ReceiveDataList)
{
int count = ReceiveDataList.Count;
for (int i = 0; i < count; i++)
{
DispenseReceiveData(ReceiveDataList[i]);
}
ReceiveDataList.Clear();
}
}
public void DispenseReceiveData(ReceiveData rData)
{
lock (ReceiveDataList)
{
ReceiveDataList.Remove(rData);
if (rData != null)
{
/* rData.ReceiveDataMstream.Close();
rData.ReceiveDataMstream.Dispose();
rData.ReceiveDataMstream = null;*/
rData.Dispose();
rData = null;
}
}
}
///
/// 清除无效连接资源
///
///
public void ClearInvalidConnectionResource(IntPtr connId)
{
try
{
List retRDatalist = new List();
lock (ReceiveDataList)
{
foreach (ReceiveData rData in ReceiveDataList)
{
if (rData.ReceiveRemoteClientInfo.ConnId == connId.ToInt32())
{
retRDatalist.Add(rData);
}
}
for (int i = 0; i < retRDatalist.Count; i++)
{
DispenseReceiveData(retRDatalist[i]);
}
retRDatalist.Clear();
}
}
catch
{
}
finally
{
System.GC.Collect();
}
}
#endregion
#region 客户端接收到的数据缓存处理方法
Dictionary _ServerToClientCacheBufferList = new Dictionary();
///
/// 收到服务发送回来的数据集合
///
public Dictionary ServerToClientCacheBufferList
{
get { return _ServerToClientCacheBufferList; }
set { _ServerToClientCacheBufferList = value; }
}
///
/// 获取收到的数据缓存区对象
///
/// 数据传输标识符
///
public ReceiveCacheBuffer GetReceiveCacheBuffer(Int64 cid)
{
lock (_ServerToClientCacheBufferList)
{
ReceiveCacheBuffer retCacheBuffer = null;
if (_ServerToClientCacheBufferList.TryGetValue(cid, out retCacheBuffer))
{
return retCacheBuffer;
}
else
{
return retCacheBuffer;
}
}
}
///
/// 添加数据缓存区对象到集合中
///
/// 数据传输标识符
///
public void AddCacheBufferToList(Int64 cid, ReceiveCacheBuffer rCacheBuffer)
{
lock (_ServerToClientCacheBufferList)
{
if (!this._ServerToClientCacheBufferList.ContainsKey(cid))
{
this._ServerToClientCacheBufferList.Add(cid, rCacheBuffer);
}
/* IntPtr ptrbytes = GetReceiveBytes(cid);
if (ptrbytes != IntPtr.Zero) {
Marshal.FreeHGlobal(ptrbytes);
ptrbytes = IntPtr.Zero;
}
DataHeader dhead = new DataHeader();
dhead.Length = bytes.Length;
int bufferSize = bytes.Length+Marshal.SizeOf(dhead);
byte[] dheadBytes = StructureToByte(dhead);
ptrbytes = Marshal.AllocHGlobal(bufferSize);
// 拷贝头数据到缓冲区
Marshal.Copy(dheadBytes, 0, ptrbytes, dheadBytes.Length);
// 拷贝数据到缓冲区剩余部分
Marshal.Copy(bytes, 0, ptrbytes + dheadBytes.Length, bytes.Length);
_ServerToClientByteList.Add(cid, ptrbytes);
bytes = null;*/
}
}
///
/// 移除指定的数据缓存区对象
///
///
public void RemoveServerToClientByteList(Int64 cid)
{
try
{
lock (_ServerToClientCacheBufferList)
{
try
{
ReceiveCacheBuffer rCacheBuffer = GetReceiveCacheBuffer(cid);
if (rCacheBuffer != null)
{
rCacheBuffer.Dispose();
rCacheBuffer = null;
}
}
catch { }
_ServerToClientCacheBufferList.Remove(cid);
}
}
finally {
System.GC.Collect();
}
}
///
/// 清除所有数据缓存区对象
///
public void ClearAllServerToClientByteList()
{
try
{
lock (_ServerToClientCacheBufferList)
{
foreach (long key in _ServerToClientCacheBufferList.Keys)
{
try
{
_ServerToClientCacheBufferList[key].Dispose();
}
catch { }
}
_ServerToClientCacheBufferList.Clear();
}
}
finally
{
System.GC.Collect();
}
}
#endregion
///
/// 进程进度报告
///
/// 运行总计数器
/// 当前进度值
/// 报告信息
public static void SetBackgroundWorker(long sumCount, long currentCount, string msg = "", System.ComponentModel.BackgroundWorker backgroundWorker = null)
{
if (backgroundWorker != null)
{
try
{
int currentProgres = Convert.ToInt32(1000f / sumCount * currentCount);
//WriteLogs("共 " + sumCount + " 字节 已接收 " + currentCount + " 字节 当前 " + currentProgres +" %");
backgroundWorker.ReportProgress(currentProgres, msg);
}
catch { }
}
}
///
/// 获取VC++ MD5
///
///
///
public static string GetVCFileMD5(string filePath)
{
string retMd5Value = "";
byte[] retByte = new byte[32];
IntPtr bufferIntPtr_File = System.Runtime.InteropServices.Marshal.AllocHGlobal(32);
if (Environment.Is64BitProcess)
{
if (VCMD5_X64.GetFileMD5(filePath, bufferIntPtr_File, 32) == 0)
{
System.Runtime.InteropServices.Marshal.Copy(bufferIntPtr_File, retByte, 0, 32);
retMd5Value = Encoding.UTF8.GetString(retByte);
}
}
else
{
if (VCMD5_X86.GetFileMD5(filePath, bufferIntPtr_File, 32) == 0)
{
System.Runtime.InteropServices.Marshal.Copy(bufferIntPtr_File, retByte, 0, 32);
retMd5Value = Encoding.UTF8.GetString(retByte);
}
}
System.Array.Clear(retByte, 0, retByte.Length);
retByte = null;
if (bufferIntPtr_File != IntPtr.Zero)
{
System.Runtime.InteropServices.Marshal.FreeHGlobal(bufferIntPtr_File);
}
return retMd5Value;
}
///
/// 获取VC++ MD5
///
///
///
public static string GetVCByteMD5(byte[] bytes)
{
string retMd5Value = "";
byte[] retByte = new byte[32];
IntPtr lpBytes = System.Runtime.InteropServices.Marshal.AllocHGlobal(bytes.Length);
System.Runtime.InteropServices.Marshal.Copy(bytes, 0, lpBytes, bytes.Length);
IntPtr bufferIntPtr = System.Runtime.InteropServices.Marshal.AllocHGlobal(32);
if (Environment.Is64BitProcess)
{
if (VCMD5_X64.GetByteMD5(lpBytes, bytes.Length, bufferIntPtr) == 0)
{
System.Runtime.InteropServices.Marshal.Copy(bufferIntPtr, retByte, 0, 32);
retMd5Value = Encoding.UTF8.GetString(retByte);
}
}
else
{
if (VCMD5_X86.GetByteMD5(lpBytes, bytes.Length, bufferIntPtr) == 0)
{
System.Runtime.InteropServices.Marshal.Copy(bufferIntPtr, retByte, 0, 32);
retMd5Value = Encoding.UTF8.GetString(retByte);
}
}
if (bufferIntPtr != IntPtr.Zero)
{
System.Runtime.InteropServices.Marshal.FreeHGlobal(bufferIntPtr);
}
if (lpBytes != IntPtr.Zero)
{
System.Runtime.InteropServices.Marshal.FreeHGlobal(lpBytes);
}
return retMd5Value;
}
///
/// 获取VC++ MD5
///
///
///
public static string GetVCStringMD5(string str)
{
string retMd5Value = "";
byte[] retByteUtf8 = Encoding.UTF8.GetBytes(str);
string Gb2313 = Encoding.GetEncoding("gb2312").GetString(retByteUtf8);
byte[] retByte = new byte[32];
IntPtr bufferIntPtr = System.Runtime.InteropServices.Marshal.AllocHGlobal(32);
if (Environment.Is64BitProcess)
{
if (VCMD5_X64.GetStringMD5(Gb2313, bufferIntPtr, 32) == 0)
{
System.Runtime.InteropServices.Marshal.Copy(bufferIntPtr, retByte, 0, 32);
retMd5Value = Encoding.UTF8.GetString(retByte);
}
}
else
{
if (VCMD5_X86.GetStringMD5(Gb2313, bufferIntPtr, 32) == 0)
{
System.Runtime.InteropServices.Marshal.Copy(bufferIntPtr, retByte, 0, 32);
retMd5Value = Encoding.UTF8.GetString(retByte);
}
}
if (bufferIntPtr != IntPtr.Zero)
{
System.Runtime.InteropServices.Marshal.FreeHGlobal(bufferIntPtr);
}
return retMd5Value;
}
///
/// 是否FIPS出错
///
static bool isFIPSError = false;
///
/// 获取文件的MD5值
///
///
///
public static string GetMD5HashFromFile(byte[] byets)
{
try
{
if (!isFIPSError)
{
try
{
System.Security.Cryptography.MD5 md5 = new System.Security.Cryptography.MD5CryptoServiceProvider();
byte[] retVal = md5.ComputeHash(byets);
StringBuilder sb = new StringBuilder();
for (int i = 0; i < retVal.Length; i++)
{
sb.Append(retVal[i].ToString("x2"));
}
byets = null;
return sb.ToString();
}
catch //(Exception ex)
{
isFIPSError = true;
return GetVCByteMD5(byets);
//throw new Exception("GetMD5HashFromFile() fail,error:" + ex.Message);
}
}
else
{
return GetVCByteMD5(byets);
}
}
catch (Exception ex)
{
throw new Exception("GetMD5HashFromFile() fail,error:" + ex.Message);
}
}
///
/// 获取文件的MD5值
///
///
///
public static string GetMD5HashFromFile(string fileName)
{
try
{
if (!isFIPSError)
{
System.IO.FileStream file = null;
try
{
file = new System.IO.FileStream(fileName, System.IO.FileMode.Open);
}
catch (Exception ex)
{
throw new Exception("验证MD5时打开文件出失败:" + ex.Message);
}
try
{
System.Security.Cryptography.MD5 md5 = new System.Security.Cryptography.MD5CryptoServiceProvider();
byte[] retVal = md5.ComputeHash(file);
StringBuilder sb = new StringBuilder();
for (int i = 0; i < retVal.Length; i++)
{
sb.Append(retVal[i].ToString("x2"));
}
System.Array.Clear(retVal, 0, retVal.Length);
retVal = null;
return sb.ToString();
}
catch //(Exception ex)
{
isFIPSError = true;
return GetVCFileMD5(fileName);
// throw new Exception("GetMD5HashFromFile() fail,error:" + ex.Message);
}
finally
{
file.Close();
file.Dispose();
}
}
else
{
return GetVCFileMD5(fileName);
}
}
catch (Exception ex)
{
throw new Exception("GetMD5HashFromFile() fail,error:" + ex.Message);
}
}
///
/// 验证两个MD5值是否相同
///
///
///
///
public static bool VerifyMd5Hash(string md51, string md52)
{
if (md51.Trim().ToUpper() == md52.Trim().ToUpper())
{
return true;
}
else
{
return false;
}
}
}
public class VCMD5_X86
{
[System.Runtime.InteropServices.DllImport("lyfzMD5_x86.dll")]
public static extern int GetStringMD5(string lpString, IntPtr pResult, int length);
[System.Runtime.InteropServices.DllImport("lyfzMD5_x86.dll")]
public static extern int GetFileMD5(string lpFilepath, IntPtr pResult, int length);
[System.Runtime.InteropServices.DllImport("lyfzMD5_x86.dll")]
public static extern int GetByteMD5(IntPtr lpBytes, int nInputlen, IntPtr pResult);
}
public class VCMD5_X64
{
[System.Runtime.InteropServices.DllImport("lyfzMD5_x64.dll")]
public static extern int GetStringMD5(string lpString, IntPtr pResult, int length);
[System.Runtime.InteropServices.DllImport("lyfzMD5_x64.dll")]
public static extern int GetFileMD5(string lpFilepath, IntPtr pResult, int length);
[System.Runtime.InteropServices.DllImport("lyfzMD5_x64.dll")]
public static extern int GetByteMD5(IntPtr lpBytes, int nInputlen, IntPtr pResult);
}
}