【发布时间】:2020-08-26 21:50:34
【问题描述】:
有一些方法可以精确确定给定路径是文件还是文件夹?
如果是,可以举个例子吗?提前致谢。
【问题讨论】:
标签: windows delphi delphi-10.3-rio
有一些方法可以精确确定给定路径是文件还是文件夹?
如果是,可以举个例子吗?提前致谢。
【问题讨论】:
标签: windows delphi delphi-10.3-rio
您可以使用 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;
【讨论】:
INVALID_FILE_ATTRIBUTES来检查文件/文件夹是否存在?
FILE_ATTRIBUTE_REPARSE_POINT,这需要更多的工作来确定目标文件/文件夹是否真的存在。