如何在Delphi 11.3 Alexandria中获取等效于ICACLS.EXE的文件权限
在Delphi 11.3中获取Windows文件/文件夹权限(模拟
icacls /save格式) 你可以直接调用Windows原生API实现类似icacls /save的权限获取功能,核心是通过安全API提取文件的**自主访问控制列表(DACL)**并转换为SDDL(安全描述符定义语言)格式——这正是icacls输出的底层格式。
实现步骤与代码
首先引用必要的单元:
uses Windows, SysUtils, AclAPI, SecurityAPI;
实现权限获取函数:
function GetFilePermissions(const FilePath: string): string; var pSD: PSECURITY_DESCRIPTOR; SDDLStr: PWideChar; FileName: string; SDDLPart: string; begin Result := ''; // 获取文件安全描述符(仅请求DACL信息) if GetNamedSecurityInfo(PWideChar(FilePath), SE_FILE_OBJECT, DACL_SECURITY_INFORMATION, nil, nil, nil, nil, @pSD) <> ERROR_SUCCESS then Exit; try // 将二进制安全描述符转换为SDDL字符串 if not ConvertSecurityDescriptorToStringSecurityDescriptor(pSD, SDDL_REVISION_1, DACL_SECURITY_INFORMATION, @SDDLStr, nil) then Exit; try FileName := ExtractFileName(FilePath); SDDLPart := string(SDDLStr); // 提取DACL部分(对应icacls输出的D:开头片段) if Pos('D:', SDDLPart) > 0 then SDDLPart := Copy(SDDLPart, Pos('D:', SDDLPart), MaxInt); // 拼接成icacls风格的输出格式 Result := FileName + sLineBreak + SDDLPart; finally LocalFree(HLOCAL(SDDLStr)); end; finally LocalFree(HLOCAL(pSD)); end; end;
调用示例(比如在按钮点击事件中):
procedure TForm1.Button1Click(Sender: TObject); var Perms: string; begin Perms := GetFilePermissions('C:\Test\Abc'); if Perms <> '' then Memo1.Lines.Text := Perms else ShowMessage('获取权限失败,错误码:' + IntToStr(GetLastError)); end;
关键细节说明
GetNamedSecurityInfo:从文件对象提取安全描述符,指定DACL_SECURITY_INFORMATION表示仅获取访问控制列表数据。ConvertSecurityDescriptorToStringSecurityDescriptor:将二进制安全描述符转换为可读的SDDL字符串,与icacls输出的格式完全匹配。- 代码中提取
D:开头的片段,因为icacls /save仅输出DACL内容,完整SDDL可能包含所有者、组等额外信息。
如果需要解析更细粒度的权限项(比如把FA转为"完全控制"、AU转为"已认证用户"),可以拆分SDDL中每个(...)内的字段,这些字段对应ACE(访问控制项)的类型、继承标志、权限掩码、用户/组SID缩写等。
内容的提问来源于stack exchange,提问作者Seekr
相关产品推荐
相关产品推荐

