Author: Lou Adler
I am trying to write a simple backup utility for my projects. The utility
recursivley searches folders looking for *.dpr files when it finds one it looks to
see if a *.dof file is available and then extracts the FileVersion number from
this, using this information it then creates a zip file with all the project files
in it. It works so far and creates files like Project1-v1.0.0.0.zip. The problem is
if the file already exists in the selected backup folder I wish to increment the
file name so all versions are kept, e.g. if Project1-v1.0.0.0.zip already exists
then generate a filename of Project1-v1.0.0.0-1.zip. If Project1-v1.0.0.0-1.zip
exists then generate a file name Project1-v1.0.0.0-2.zip etc. to make sure no files
are overwritten.
Answer:
Variants are the easiest way of dealing with these properties.
1 2 function GetNextBackupFileName(AFolder, AFile: string): string;
3 var4 v, v1: Integer;
5 Body, Ext: string;
6 sr: TSearchRec;
7 8 function FileExt(FileName: string): string;
9 begin10 Result := ExtractFileExt(FileName);
11 end;
12 13 function FileBody(FileName: string): string;
14 begin15 Result := ChangeFileExt(FileName, '');
16 end;
17 18 function GetPostFix(FileName: string): Integer;
19 begin20 Result := StrToIntDef(Copy(FileBody(FileName), Length(Body) + 1, 255), 0);
21 end;
22 23 begin24 Result := AFile;
25 v := 0;
26 Body := FileBody(AFile);
27 Ext := FileExt(AFile);
28 if FindFirst(AFolder + Body + '*' + Ext, faAnyFile xor faDirectory, sr) = 0 then29 begin30 repeat31 v1 := GetPostFix(sr.Name);
32 if v1 < v then33 v := v1;
34 until35 FindNext(sr) <> 0;
36 FindClose(sr);
37 Result := Body + IntToStr(v - 1) + Ext;
38 end;
39 end;
40 41 //Used like this:42 43 procedure TForm1.Button1Click(Sender: TObject);
44 var45 BackupFolder, BaseFileName: string;
46 begin47 BackupFolder := 'C:\BackupFolder\';
48 BaseFileName := 'Project1-v1.0.0.0.zip';
49 Label1.Caption := GetNextBackupFileName(BackupFolder, BaseFileName);
50 FileClose(FileCreate(BackupFolder + Label1.Caption));
51 end;