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

查看:127
本文介绍了如何使用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 do anyway since you are using the FILE_FLAG_DELETE_ON_CLOSE flag.

BTW,有一个小你的代码中的错误。您正在创建一个临时字符串并将其分配给一个PWideChar,但是在实际使用该PWideChar之前,该String超出了范围,释放了内存。您的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天全站免登陆