File is Still in Use Error 32 How can I free it?

1k views Asked by At

I am uploading a file via the following code.

After a successful upload I am attempting to Delete the file but I am getting a 32 - File in use error.

Can anyone tell me how I can resolve this file in use error? The following code is uploading the file, but not releasing it when done..

var
  HTTP: TidHTTP;
  SSLIOHandler: TIdSSLIOHandlerSocketOpenSSL;
  PostData: TIdMultiPartFormDataStream;
  ResponseStream: TStringStream;
  Delete : Boolean;

begin
  ResponseStream := TStringStream.Create('');
  HTTP := TidHTTP.Create(nil);
  SSLIOHandler := TIdSSLIOHandlerSocketOpenSSL.Create(nil);

  try
    SSLIOHandler.SSLOptions.Method := sslvSSLv3;
    HTTP.ReadTimeout := 30000; //30 seconds
    HTTP.ConnectTimeout := 30000; //30 seconds
    HTTP.IOHandler := SSLIOHandler;
    HTTP.HTTPOptions := [hoKeepOrigProtocol];
    HTTP.ProtocolVersion := pv1_1;
    PostData := TIdMultiPartFormDataStream.Create;

    PostData.AddFormField('username', 'demo');
    PostData.AddFormField('password', 'demo');
    PostData.AddFormField('action', 'upload');
    PostData.AddFormField('accountno', 'demo');

  PostData.AddFile('uploadedfile', FileName, GetMIMETypeFromFile(FileName));

  HTTP.Request.ContentType := PostData.RequestContentType;
  HTTP.Post('http://uploadsite.com/ex/exampleAPI.asmx/Process', PostData, ResponseStream);

  if AnsiContainsStr(ResponseStream.DataString, 'Done') then
    Delete := True;

finally
  SSLIOHandler.Free;
  HTTP.Free;
  ResponseStream.Free;
end;

if Delete then
  if DeleteFile(BFlashFileName) then
    ShowMessage('Deleted')
  else ShowMessage(BFlashFileName+' not deleted, error = '+
               IntToStr(GetLastError));
1

There are 1 answers

0
Sertac Akyuz On BEST ANSWER

Call the Clear method of your TIdMultiPartFormDataStream instance before attempting to delete the file. If you don't need it anymore, freeing it will also amount to same (i.e. PostData.Free). Currently, it looks like you're leaking your PostData variable.

While TIdMultiPartFormDataStream is clearing its Fields collection, the file stream created by the AddFile method will be destroyed closing the file's handle.