如何检查给定路径是文件还是文件夹?
How to check if given path is FILE or FOLDER?
有什么方法可以精确确定给定路径是文件还是文件夹?
如果是,请举个例子好吗?提前致谢。
可以使用RTL的TPath.GetAttributes()
, TFile.GetAttributes()
or 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()
or 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;
有什么方法可以精确确定给定路径是文件还是文件夹?
如果是,请举个例子好吗?提前致谢。
可以使用RTL的TPath.GetAttributes()
, TFile.GetAttributes()
or 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()
or 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;