1. Variant和Stream的互换
procedure VarToStream(var AStm: TStream; var AOvar: Olevariant);
var
p: Pointer;
begin
AStm:= TMemoryStream.Create;
AStm.Position := 0;
p := VarArrayLock(AOvar);
AStm.Write(p^, VarArrayHighBound(AOvar, 1));
VarArrayUnlock(AOvar);
end;
procedure StreamToVar(var AStm: TStream; var AOvar: Olevariant);
var
p: Pointer;
begin
AOvar := VarArrayCreate([0, AStm.Size - 1], VarByte);
p := VarArrayLock(AOvar);
AStm.ReadBuffer(p^, AStm.Size);
VarArrayUnlock(AOvar);
end;
var
p: Pointer;
begin
AStm:= TMemoryStream.Create;
AStm.Position := 0;
p := VarArrayLock(AOvar);
AStm.Write(p^, VarArrayHighBound(AOvar, 1));
VarArrayUnlock(AOvar);
end;
procedure StreamToVar(var AStm: TStream; var AOvar: Olevariant);
var
p: Pointer;
begin
AOvar := VarArrayCreate([0, AStm.Size - 1], VarByte);
p := VarArrayLock(AOvar);
AStm.ReadBuffer(p^, AStm.Size);
VarArrayUnlock(AOvar);
end;
2. 判断文件是否在用
{createfile里面的第三个参数为dwShareMode ,使用如下(详见createfile的API)
[in] The sharing mode of an object, which can be read, write, both, or none.
You cannot request a sharing mode that conflicts with the access mode that is specified in an open request that has an open handle, because that would result in the following sharing violation: ERROR_SHARING_VIOLATION). For more information, see Creating and Opening Files.
If this parameter is 0 (zero) and CreateFile succeeds, the object cannot be shared and cannot be opened again until the handle is closed. For more information, see the Remarks section of this topic.
}
function IsFileInUse(const AFileName: string): Boolean;
var
HFileRes: HFILE;
begin
Result := false;
if not FileExists(AFileName) then //如果文件不存在
exit;
HFileRes := CreateFile(pchar(AFileName), GENERIC_READ or GENERIC_WRITE,
0 {this is the trick!}, nil, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, 0);
Result := (HFileRes = INVALID_HANDLE_VALUE);
if not Result then
CloseHandle(HFileRes);
end;
[in] The sharing mode of an object, which can be read, write, both, or none.
You cannot request a sharing mode that conflicts with the access mode that is specified in an open request that has an open handle, because that would result in the following sharing violation: ERROR_SHARING_VIOLATION). For more information, see Creating and Opening Files.
If this parameter is 0 (zero) and CreateFile succeeds, the object cannot be shared and cannot be opened again until the handle is closed. For more information, see the Remarks section of this topic.
}
function IsFileInUse(const AFileName: string): Boolean;
var
HFileRes: HFILE;
begin
Result := false;
if not FileExists(AFileName) then //如果文件不存在
exit;
HFileRes := CreateFile(pchar(AFileName), GENERIC_READ or GENERIC_WRITE,
0 {this is the trick!}, nil, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, 0);
Result := (HFileRes = INVALID_HANDLE_VALUE);
if not Result then
CloseHandle(HFileRes);
end;