I use this code to send a file to a client.
procedure TForm1.IdTCPServer1Execute(AThread: TIdPeerThread);
var
hFile : THandle;
FileBuff : array [0..1023] of byte;
dwRead : DWORD;
Recieved : String;
begin
Recieved := Athread.Connection.ReadLn;
if Recieved = 'FILE' then begin
Memo1.Lines.Add('Sending File...');
hFile := CreateFileW('FILE.bin',
GENERIC_READ, FILE_SHARE_READ, nil, OPEN_EXISTING, 0, 0);
if hFile = INVALID_HANDLE_VALUE then exit;
SetFilePointer(hFile, 0, nil, FILE_BEGIN);
while true do begin
ReadFile(hFile, FileBuff[0], 1024, dwRead, nil);
if dwRead <= 0 then break;
Athread.Connection.WriteBuffer(FileBuff[0], dwRead);
end;
CloseHandle (hFile);
Athread.Connection.Disconnect;
end;
end;
This works like a charm but if the client disconnects while the file is sending, Indy terminates the Execute Thread immediately so the filehandle is still open! Is there a way to close the filehandle after the client disconnects?
Thank you for your help.
try..finally..end
? – RRUZ