Adam Mitchell Adam Mitchell - 2 months ago 49
Pascal Question

Inno Setup FileCopy failing

I'm working on an installer that needs to create a backup of a directory prior to installing. The method I implement is purely to copy all files from the current directory to a new directory and then I am free to overwrite files (my installer) in the old directory.

However, I receive a prompt indicating

file copy failed
, but I just cannot understand why it doesn't work. My error message prints the correct directory\filename and I can verify that they exist and aren't open in any external programs.

Below is the code, taken (and modified slightly) from: http://blogs.candoerz.com/question/139833/inno-setup-copy-folder-subfolders-and-files-recursively-in-code-section.aspx

function DirectoryCopy(SourcePath, DestPath: string): boolean;
var
FindRec: TFindRec;
SourceFilePath: string;
DestFilePath: string;
begin
if FindFirst(SourcePath + '\*', FindRec) then begin
try
repeat
if (FindRec.Name <> '.') and (FindRec.Name <> '..') then begin
SourceFilePath := SourcePath + '\' + FindRec.Name;
DestFilePath := DestPath + '\' + FindRec.Name;
if FindRec.Attributes and FILE_ATTRIBUTE_DIRECTORY = 0 then begin
if FileCopy(SourceFilePath, DestFilePath, False) then begin
Result := True;
MsgBox('Copy Worked!', mbInformation, MB_OK);
end else begin
Result := False;
MsgBox('Copy Failed!'+SourceFilePath, mbInformation, MB_OK);
end;
end else begin
if CreateDir(DestFilePath) then begin
Result := True;
MsgBox('Created Dir!', mbInformation, MB_OK);
DirectoryCopy(SourceFilePath, DestFilePath);
end else begin
Result := False;
MsgBox('Failed to create Dir!', mbInformation, MB_OK);
end;
end;
end;
until not FindNext(FindRec);
finally
FindClose(FindRec);
end;
end else begin
Result := False;
MsgBox('Failed to List!', mbInformation, MB_OK);
end;
end;

Answer

I suspect that the directory you are trying to copy to doesn't exist. You need to create the directory first using CreateDir or ForceDirectories. The file functions (including Martin's DirectoryCopy function, which uses these internal functions) require the directory to exist or they will fail. They will not automatically create the path for you. It is a pity this isn't documented anywhere (that I could find, although someone may be able to correct me on that) as it caught me out for a while too.

The original link to Martin's DirectoryCopy function is available here.