Forum > General

File creation error in Windows, Linux is OK

(1/1)

edvard:
OK, I finally got a project mostly done, so I'm preparing to release (I'll announce it on this board so you all can flame critique my programming skills).

I have a bit of a strange error on Windows, however.  Take this piece of code, which writes a new configuration file if none is found
(PBConfig is defined as a TStringlist, and freed later in the code, CFGFile is a function that returns the result of GetAppConfigFile(false)):

--- Code: ---procedure makeConfig;
begin
  PBConfig := TStringList.Create;
  PBConfig.Add('UserKey=');
  PBConfig.Add('Format=0');
  PBConfig.Add('Expire=0');
  PBConfig.Add('Private=0');
  PBConfig.SaveToFile(CFGFile);
end;
--- End code ---

If I leave it as-is, I get a "Project pastequick raised exception class 'EFCreateError' with message:  Unable to create file "C:\users\me\AppData\local\pastequick\pastequick.cfg""
No spaces in the path, so I couldn't really figure that out, then I thought "Maybe the error is due to it trying to write to a file that doesn't exist, so why don't I create the file first with FileCreate?"
Great idea, says /me

--- Code: ---procedure makeConfig;
begin
  FileCreate(CFGFile);
 ...
--- End code ---

Same error, so now I do this:

--- Code: ---procedure makeConfig;
begin
  ForceDirectories(GetAppConfigDir(false));
  FileCreate(CFGFile);
 ...
--- End code ---

Now it's giving me an error that it can't read the file, but the file is created.  The file that is created  is 0 kb. ???
A second compile attempt gives the error:
"project pastequick raised exception class 'EConvertError' with message: "" is an invalid integer"

WTH? %)

sapper:
You are on the right track.

The subdirectory
--- Quote ---\pastequick
--- End quote ---
needs to be created.

This test code worked for me.


--- Code: ---procedure TForm1.Button1Click(Sender: TObject);
var
   PBConfig : TStringList;
   path : string;
begin
  PBConfig := TStringList.Create;
  PBConfig.Add('UserKey=');
  PBConfig.Add('Format=0');
  PBConfig.Add('Expire=0');
  PBConfig.Add('Private=0');
  path := GetAppConfigFile(False);
  if ForceDirectories(ExtractFilePath(path)) then
     PBConfig.SaveToFile(path)
  else
      ShowMessage('Unable to create path');
  PBConfig.Free;
end;   
--- End code ---
       

EDIT: If using FileCreate you should probably use the THandle returned to close the file with FileClose before attempting to write/read since I assume you are not using FileWrite or FileRead.

edvard:
Thanks! That works great.  I'll credit you in the source, and I'll post about my project tomorrow.  I'm going to bed now...

Navigation

[0] Message Index

Go to full version