Check ik file exist

Peter Kiers
Peter Kiers used Ask the Experts™
on
Dear experts,

I have this to load and save the 3 listviews to file.

procedure TMainForm.FormClose(Sender: TObject; var Action: TCloseAction);
begin
  SaveListViewToFile(lstvGlucose, 'Glucose.sav');
  SaveListViewToFile(lstvBolus, 'Bolus.sav');
  SaveListViewToFile(lstvFoodDB, 'FoodDB.sav');
end;
(*---------------------------------------------------*)
procedure TMainForm.FormCreate(Sender: TObject);
begin
  LoadListViewToFile(lstvGlucose, 'Glucose.sav');
  LoadListViewToFile(lstvBolus, 'Bolus.sav');
  LoadListViewToFile(lstvFoodDB, 'FoodDB.sav');
end;

But when I start my application the first time the files doesn't exits yet.
so, I get 3 times a error message. How can I prevent this.
That the programm first look if the fileexist otherwist create it.

P
Comment
Watch Question

Do more with

Expert Office
EXPERT OFFICE® is a registered trademark of EXPERTS EXCHANGE®

Commented:
Try to check this way :

if FileExists(File_Name)  then  DeleteFile(File_Name);
Peter KiersOperator

Author

Commented:
It has to be like this:

If file does not exits in the application-folder
then create one.

P.

Commented:
If I understand you correctly,  this will do it :

procedure TMainForm.FormCreate(Sender: TObject);
begin
  if FileExists('Glucose.sav')  then  LoadListViewToFile(lstvGlucose, 'Glucose.sav');
  if FileExists('Bolus.sav')      then  LoadListViewToFile((lstvBolus, 'Bolus.sav');
  if FileExists('FoodDB.sav')  then  LoadListViewToFile(lstvFoodDB, 'FoodDB.sav');
end;

procedure TMainForm.FormClose(Sender: TObject; var Action: TCloseAction);
begin
   if FileExists('Glucose.sav')  then   DeleteFile('Glucose.sav');
   SaveListViewToFile(lstvGlucose, 'Glucose.sav');
   if FileExists('Bolus.sav')  then   DeleteFile('Bolus.sav');
   SaveListViewToFile(lstvBolus, 'Bolus.sav');
   if FileExists('FoodDB.sav')  then   DeleteFile('FoodDB.sav');
   SaveListViewToFile(lstvFoodDB, 'FoodDB.sav');
Peter KiersOperator

Author

Commented:
I found out myself:

procedure TMainForm.FormCreate(Sender: TObject);
begin
  PgCtrlMain.ActivePage := tbshGlucose;
  if FileExists(ExtractFilePath(Application.ExeName) + 'Glucose.sav') then
  LoadListViewToFile(lstvGlucose, 'Glucose.sav');
  if FileExists(ExtractFilePath(Application.ExeName) + 'Bolus.sav') then
  LoadListViewToFile(lstvBolus, 'Bolus.sav');
  if FileExists(ExtractFilePath(Application.ExeName) + 'FoodDB.sav') then
  LoadListViewToFile(lstvFoodDB, 'FoodDB.sav');
end;
Commented:
Founded solution is very creative, but by default the files will be saved in (or loaded from) applications folder therefore
   ExtractFilePath(Application.ExeName)    is   unnecessary.

Do more with

Expert Office
Submit tech questions to Ask the Experts™ at any time to receive solutions, advice, and new ideas from leading industry professionals.

Start 7-Day Free Trial