【问题标题】:How to check if given path is FILE or FOLDER?如何检查给定的路径是文件还是文件夹?
【发布时间】:2020-08-26 21:50:34
【问题描述】:

有一些方法可以精确确定给定路径是文件还是文件夹?

如果是,可以举个例子吗?提前致谢。

【问题讨论】:

    标签: windows delphi delphi-10.3-rio


    【解决方案1】:

    您可以使用 RTL 的 TPath.GetAttributes()TFile.GetAttributes()TDirectory.GetAttributes() 方法,例如:

    uses
      ..., System.IOUtils;
    
    try
      if TFileAttribute.faDirectory in TPath{|TFile|TDirectory}.GetAttributes(path) then
      begin
        // path is a folder ...
      end else
      begin
        // path is a file ...
      end;
    except
      // error ...
    end;
    

    或者,您可以直接使用 Win32 API GetFileAttributes()GetFileAttributesEx() 函数,例如:

    uses
      ..., Winapi.Windows;
    
    var
      attrs: DWORD;
    begin
      attrs := Windows.GetFileAttributes(PChar(path));
      if attrs = INVALID_FILE_ATTRIBUTES then
      begin
        // error ...
      end
      else if (attrs and FILE_ATTRIBUTE_DIRECTORY) <> 0 then
      begin
        // path is a folder ...
      end else
      begin
        // path is a file ...
      end;
    end;
    
    uses
      ..., Winapi.Windows;
    
    var
      data: WIN32_FILE_ATTRIBUTE_DATA;
    begin
      if not Windows.GetFileAttributesEx(PChar(path), GetFileExInfoStandard, @data) then
      begin
        // error ...
      end
      else if (data.dwFileAttributes and FILE_ATTRIBUTE_DIRECTORY) <> 0 then
      begin
        // path is a folder ...
      end else
      begin
        // path is a file ...
      end;
    end;
    

    【讨论】:

    • 看到上面的WIN32 API选项,是否可以测试INVALID_FILE_ATTRIBUTES来检查文件/文件夹是否存在?
    • Potentially yes,只要你不需要处理FILE_ATTRIBUTE_REPARSE_POINT,这需要更多的工作来确定目标文件/文件夹是否真的存在。
    猜你喜欢
    • 2015-07-30
    • 2017-02-11
    • 1970-01-01
    • 2018-12-18
    • 1970-01-01
    • 2013-03-15
    • 2012-01-15
    • 2011-12-26
    • 2013-08-14
    相关资源
    最近更新 更多