(*
* 单元说明: 文件/流的加密解密方法(For Delphi 6-7)
*
* 软件来源: http://www.go-neumann.com
* http://www.inbytes.net
*
* 作 者: neumann@163.com
*
* 使用说明: 此文件的代码可以直接编译使用,
* 您可以根据需要编写自己的加密/解密代码.
*
* 声 明: 以下代码属作者原创, 请转载时保留本信息.
*
*)
unit uCompress;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, ComCtrls, Dialogs;
// 压缩/解压文件
procedure CompressFile(Source, Target: String); stdcall;
procedure DecompressFile(Source, Target: String); stdcall;
// 压缩/解压文件到流
procedure CompressToStream(FileName: String; Stream: TStream); stdcall;
procedure DecompressToStream(FileName: String; Stream: TStream); stdcall;
// 压缩/解压流
procedure CompressStream(InStream, OutStream: TStream); stdcall;
procedure DecompressStream(InStream, OutStream: TStream); stdcall;
implementation
uses
ZLib;
const
COMPRESS_ERROR = ''压缩文件时出现内部错误:'';
DECOMPRESS_ERROR = ''解压文件时出现内部错误:'';
COMPRESS_STRM_ERROR = ''压缩流时出现内部错误:'';
DECOMPRESS_STRM_ERROR = ''解压流时出现内部错误:'';
BufSize = $4096;
// 压缩文件
procedure CompressFile(Source, Target: String);
var
i: Integer;
Buf: array[0..BufSize] of byte;
ComStream: TCompressionStream;
InStream, OutStream: TFileStream;
begin
if not FileExists(Source) then
Exit;
InStream := Nil;
OutStream := nil;
ComStream := nil;
try
// 生成流
InStream := TFileStream.Create(Source, fmOpenRead OR fmShareDenyNone);
OutStream := TFileStream.Create(Target, fmCreate OR fmShareDenyWrite);
ComStream := TCompressionStream.Create(clMax, OutStream);
// 压缩流
for i := 1 to (InStream.Size div BufSize) do begin
InStream.ReadBuffer(Buf, BufSize);
ComStream.Write(Buf, BufSize);
end;
i := InStream.Size mod BufSize;
if (i > 0) then begin
InStream.ReadBuffer(Buf, i);
ComStream.Write(Buf, i);
End;
InStream.Free;
InStream := nil;
// 注先后
ComStream.Free;
ComStream := nil;
// 在此写加密流代码(要先释放 ComStream)
// EncryptStream(OutStream);
OutStream.Free;
OutStream := nil;
except
on E: Exception do begin
if (InStream <> nil) then
InStream.Free;
if (OutStream <> nil) then
OutStream.Free;
if (ComStream <> nil) then
ComStream.Free;
MessageDlg(COMPRESS_ERROR + #10 + E.Message, mtError, [mbOk], 0);
end;
end;
end;
// 解压文件
procedure DecompressFile(Source, Target: String);
var
i: Integer;
Buf: array[0..BufSize] of Byte;
DecomStream: TDecompressionStream;
MemStream: TMemoryStream;
OutStream: TFileStream;
begin
if not FileExists(Source) then
Exit;
MemStream := Nil;
OutStream := nil;
DecomStream := nil;
try
// 生成流
// 先读文件到 MemStream 中解密(Source 只读).
// DecomStream 的开始位置 = MemStream.Position
MemStream := TMemorySt