Forum > Windows

Test if I could write to a certain file

(1/4) > >>

dietmar:
Hi,

does anyone have a test routine ready to determine whether I am allowed to write to a specific file?
The caveat is, that this file may be already existent, but should not be changed (yet).
Using Unix, I would just use fpaccess - is there an equivalent for windows?

Thx,
--Dietmar

Bart:
On Windows: try to open it in write mode (fmOpenWrite or fmShareDenyWrite).
As long as you don't do any writing, the file won't change.

Bart

lucamar:
Alternatively you could use SysUtils.FileIsReadOnly(), e.g.

--- Code: Pascal  [+][-]window.onload = function(){var x1 = document.getElementById("main_content_section"); if (x1) { var x = document.getElementsByClassName("geshi");for (var i = 0; i < x.length; i++) { x[i].style.maxHeight='none'; x[i].style.height = Math.min(x[i].clientHeight+15,306)+'px'; x[i].style.resize = "vertical";}};} ---{ uses sysutils }function FileIsWriteable(const AFilename; String): Boolean;begin  Result := FileExists(AFilename) and not FileIsReadOnly(AFilename);end;
Never mind; all it does elsewhere than on *nix is to check the file attributes, which doesn't guarantee that it can indeed can written to :-[

dietmar:
I now tried:

function FileIsWriteable(fn: String) : Boolean;
begin
  //exit(FileOpen(fn,fmOpenWrite or fmShareDenyWrite)<>-1);
  exit(FileOpen(fn,fmOpenWrite or fmShareDenyWrite)<>THandle(-1));
end;

Both variants don't work and always return TRUE. The first variant additionally gives a strange compiler warning.

--Dietmar

PascalDragon:

--- Quote from: dietmar on August 02, 2021, 03:17:05 pm ---I now tried:

function FileIsWriteable(fn: String) : Boolean;
begin
  //exit(FileOpen(fn,fmOpenWrite or fmShareDenyWrite)<>-1);
  exit(FileOpen(fn,fmOpenWrite or fmShareDenyWrite)<>THandle(-1));
end;

Both variants don't work and always return TRUE. The first variant additionally gives a strange compiler warning.

--- End quote ---

Independent of if it works for your purpose or not: if a valid handle is returned you should close it with FileClose before leaving FileIsWriteable otherwise you'll leak handles.

Navigation

[0] Message Index

[#] Next page

Go to full version