您的位置:首页 > 其它

根据文件路径检测文件大小并检测是否正在被占用

2016-11-11 00:00 387 查看
function CheckFileSize(sPath: string): Int64;
var
FilePath: AnsiString;
FStream:TFileStream;
bOpen:Boolean;
//判断文件FileName是否正在被打开/使用
function IsFileInUse(const FileName: string): boolean;
var
HFileRes: HFILE;
begin
if not FileExists(FileName) then
begin
Result := False;
Exit;
end;
try
HFileRes := CreateFile(pchar(FileName), GENERIC_READ,
0 {this is the trick!}, nil, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, 0);
Result := (HFileRes = INVALID_HANDLE_VALUE);
if not Result then
CloseHandle(HFileRes);
except
Result := true;
end;
end;
begin
try
try
IsFileInUse(sPath);
if FileExists(sPath) then
begin
bOpen := false;
while not bOpen do
begin
try
IsFileInUse(sPath);
FStream := TFileStream.Create(sPath, fmOpenWrite);
bOpen := true;
except on E: Exception do
bOpen := false;
end;
end;
FStream.Position := FStream.Size;
Result := FStream.Size;
end
else
begin
FStream := TFileStream.Create(sPath, fmCreate);
Result := 0;
end;
except
on e: Exception do
begin
Result := -2;
end;
end;
finally
FreeAndNil(FStream);
end;
end;
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: