Go Premium for a chance to win a PS4. Enter to Win

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 251
  • Last Modified:

filename collision

Hi,

  is there an algorithm that will prevent a rename collision. or should i say if i have a file name
  file1.txt and file2.txt   and i will rename file2.txt to file1.txt it will not prompt for filename exists
  but instead it will rename it to file1a.txt and so on and so forth?


0
aerokevs
Asked:
aerokevs
1 Solution
 
mokuleCommented:
// procedure renames file OldName to NewName
// if file NewName exists the name is expanded with _NNN
// starting from _001
// until free number is found

procedure MyRenameFile(OldName,NewName: string);
var
  TempName,Ext : string;
  P: integer;
  Cnt: integer;
begin
  if FileExists(NewName) then
    begin
    Ext := ExtractFileExt(NewName);
    P := Pos(Ext,NewName);
    TempName := Copy(NewName,1,P-1);
    Cnt := 1;
    repeat
      begin
      NewName := Format('%s_%3.3d%s',[TempName,Cnt,Ext]);
      Inc(Cnt);
      end;
    until not FileExists(NewName);
    end;
  RenameFile(OldName,NewName);
end;
0

Featured Post

Keep up with what's happening at Experts Exchange!

Sign up to receive Decoded, a new monthly digest with product updates, feature release info, continuing education opportunities, and more.

Tackle projects and never again get stuck behind a technical roadblock.
Join Now