如何使用 Delphi 测试目录是否可写? [英] How can I use Delphi to test if a Directory is writeable?

查看:17
本文介绍了如何使用 Delphi 测试目录是否可写?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

目前我使用这个函数,基于 JCL 代码,工作正常:

Currently I use this function, based on JCL code, which works fine:

function IsDirectoryWriteable(const AName: string): Boolean;
var
  FileName: PWideChar;
  H: THandle;
begin
  FileName := PWideChar(IncludeTrailingPathDelimiter(AName) + 'chk.tmp');

  H := CreateFile(FileName, GENERIC_READ or GENERIC_WRITE, 0, nil,
    CREATE_NEW, FILE_ATTRIBUTE_TEMPORARY or FILE_FLAG_DELETE_ON_CLOSE, 0);

  Result := H <> INVALID_HANDLE_VALUE;

  DeleteFile(FileName);
end;

有什么我可以改进的标志吗?可以在不实际创建文件的情况下完成测试吗?或者这个功能是否已经在 RTL 或 Jedi 库之一中可用?

Is there anything I could improve with the flags? Can the test be done without actually creating a file? Or is this functionality even already available in one of the RTL or Jedi libraries?

推荐答案

实际上写入目录是确定目录是否可写的最简单方法.可供单独检查的安全选项太多,即便如此,您也可能会错过某些内容.

Actually writing to the directory is the simpliest way to determine if the directory is writable. There are too many security options available to check individually, and even then you might miss something.

您还需要在调用 DeleteFile() 之前关闭打开的句柄.由于您使用的是 FILE_FLAG_DELETE_ON_CLOSE 标志,因此您无论如何都不需要调用它.

You also need to close the opened handle before calling DeleteFile(). Which you do not need to call anyway since you are using the FILE_FLAG_DELETE_ON_CLOSE flag.

顺便说一句,您的代码中有一个小错误.您正在创建一个临时 String 并将其分配给 PWideChar,但 String 超出范围,释放内存,在 之前>PWideChar 实际使用.您的 FileName 变量应该是 String 而不是 PWideChar.在调用 CreateFile() 时进行类型转换,而不是之前.

BTW, there is a small bug in your code. You are creating a temporary String and assigning it to a PWideChar, but the String goes out of scope, freeing the memory, before the PWideChar is actually used. Your FileName variable should be a String instead of a PWideChar. Do the type-cast when calling CreateFile(), not before.

试试这个:

function IsDirectoryWriteable(const AName: string): Boolean; 
var 
  FileName: String; 
  H: THandle; 
begin 
  FileName := IncludeTrailingPathDelimiter(AName) + 'chk.tmp'; 
  H := CreateFile(PChar(FileName), GENERIC_READ or GENERIC_WRITE, 0, nil, 
    CREATE_NEW, FILE_ATTRIBUTE_TEMPORARY or FILE_FLAG_DELETE_ON_CLOSE, 0); 
  Result := H <> INVALID_HANDLE_VALUE; 
  if Result then CloseHandle(H);
end;

这篇关于如何使用 Delphi 测试目录是否可写?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆