问题描述
有某种方法可以精确确定给定路径是FILE还是FOLDER?
如果是,请举个例子吗?预先感谢。
解决方法
您可以使用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;