Delete a file permanently

Spread the love

Delete a file permanently with delphi

If you want to get rid of a file normally you just delete it.
But someone else can undelete it if the file hasn’t been wiped correctly.
For security purposes, to insure that certain files are permanently
gone, the WipeFile procedure writes over the data in the file with
random characters and then erases it.

procedure WipeFile(FileName: string);
var
  buffer: array [0..4095] of Byte;
  max, n: LongInt;
  i: Integer;
  fs: TFileStream;

  procedure RandomizeBuffer;
  var
    i: Integer;
  begin
    for i := Low(buffer) to High(buffer) do
      buffer[i] := Random(256);
  end;
begin
  fs := TFilestream.Create(FileName, fmOpenReadWrite or fmShareExclusive);
  try
    for i := 1 to 3 do
    begin
      RandomizeBuffer;
      max := fs.Size;
      fs.Position := 0;
      while max > 0 do
      begin
        if max > SizeOf(buffer) then
          n := SizeOf(buffer)
        else
          n := max;
        fs.Write(Buffer, n);
        max := max - n;
      end;
      FlushFileBuffers(fs.Handle);
    end;
  finally
    fs.Free;
  end;
  Deletefile(FileName);
end;