It is quite easy to find whether a directory is writable or not. If we can create a file on the target directory, the directory is writable, otherwise not.

function IsDirectoryWritable(const Dir: String): Boolean;
var
  TempFile: array[0..MAX_PATH] of Char;
begin
  if GetTempFileName(PChar(Dir), 'DA', 0, TempFile) <> 0 then
    Result := Windows.DeleteFile(TempFile)
  else
    Result := False;
end;

The above function uses GetTempFileName API of Windows. When the nUnique parameter (the 3rd parameter) of GetTempFileName is zero, Windows creates the temporary file automatically and returns the unique number used for making the file name. When the returned number is not zero, that means the directory is writable and the temporary file is created successfully.

Reader's Comments »

  1. 1. By 判断目录是否可写 | 徐凡的blog on May 27, 2012 at 20:12

    […] 下面是一段delphi代码(来自http://www.delphiarea.com/articles/how-to-find-if-a-directory-is-writable/), […]