Reputation: 679
So i'm tying to use a idFTP component before any form is created. I'm calling a function that needs to check for a file on an ftp server so I need to create it.
Here's the function:
function restoreBackup(online: Boolean = TRUE): Boolean; //restores backup from server if possible, if not from disk
var
FTP: TidFTP;
begin
if online then
begin
FTP:=FTP.Create();
FTP.Host:=getConfig('ftphost');
FTP.Username:=getConfig('ftpuser');
FTP.Port:=StrToInt(getConfig('ftpport'));
FTP.Password:=getConfig('ftppass');
try
FTP.Connect;
FTP.ChangeDir(getConfig('ftpbkpdir'));
if FTP.Size('masterlist.dat')<>-1 then
begin
FTP.Get('masterlist.dat', getConfig('masterlistpath'));
end;
except
MessageDlg('Impossible de se connecter au serveur, la sauvegarde sera restaurée à partir du disque.', mtError, [mbOK], 0);
end;
end;
//restore from disk
FTP.Free;
end;
It is called from the project's source:
var
Sel: Integer;
begin
Application.Initialize;
global.initGlobal;
if not global.verifyPaths then //verify if all paths are good
begin
Sel:=MessageDlg('Un des chemins d''accès est erroné. L''application peut restaurer la dernière sauvegarde mais il se peut que certaines informations soient perdues. Voulez-vous continuer?',
mtError, [mbYes,mbNo], 0);
if Sel=6 then //6 is mrYes
begin
io.restoreBackup(); //// It gets called here.
end else
begin
Application.Terminate;
end;
end else
begin
//Create Forms
Application.Run;
end;
end.
When the function is called, I get an access violation. I'm pretty sure I'm not creating it properly but I don't know how to make it work.
Upvotes: 0
Views: 1467
Reputation: 136391
The line FTP:=FTP.Create();
should be FTP:=TidFTP.Create(nil);
. Also remember protect the resources using a try finally block.
Like this
var
FTP: TidFTP;
begin
if online then
begin
FTP:=TidFTP.Create(nil);
try
FTP.Host:=getConfig('ftphost');
FTP.Username:=getConfig('ftpuser');
FTP.Port:=StrToInt(getConfig('ftpport'));
FTP.Password:=getConfig('ftppass');
try
FTP.Connect;
FTP.ChangeDir(getConfig('ftpbkpdir'));
if FTP.Size('masterlist.dat')<>-1 then
FTP.Get('masterlist.dat', getConfig('masterlistpath'));
except
MessageDlg('Impossible de se connecter au serveur, la sauvegarde sera restaurée à partir du disque.', mtError, [mbOK], 0);
end;
finally
FTP.Free;
end;
end;
Upvotes: 3