当前位置:  开发笔记 > 后端 > 正文

如何使用Delphi在运行时创建具有所有用户的完全权限的目录?

如何解决《如何使用Delphi在运行时创建具有所有用户的完全权限的目录?》经验,为你挑选了1个好方法。

我需要在COMMONAPPDATA内创建一个目录(如果它不存在),该目录具有该计算机的每个用户的完全权限(每个人都可以读取或写入该目录).我正在寻找原生的简单代码在Delphi中执行此操作,而不使用第三部分库或组件.



1> RRUZ..:

@WarmBooter,您可以使用CreateDirectory函数来完成此任务.

看这个例子:

program Project645;

{$APPTYPE CONSOLE}

uses
  AccCtrl,
  AclApi,
  Windows,
  SysUtils;


type

  PTrusteeW = ^TTrusteeW;
  TTrusteeW = record
    pMultipleTrustee: PTrusteeW;
    MultipleTrusteeOperation: DWORD;  { MULTIPLE_TRUSTEE_OPERATION }
    TrusteeForm: DWORD;  { TRUSTEE_FORM }
    TrusteeType: DWORD;  { TRUSTEE_TYPE }
    ptstrName: PWideChar;
  end;
  TExplicitAccessW = record
    grfAccessPermissions: DWORD;
    grfAccessMode: DWORD;  { ACCESS_MODE }
    grfInheritance: DWORD;
    Trustee: TTrusteeW;
  end;



Function  CreateDirectoryFullAccess(NewDirectory:String) :Boolean;
var
    SecurityAttributes  : TSecurityAttributes;
    SecurityDescriptor  : PSecurityDescriptor;
    ExplicitAccess      : array[0..0] of TExplicitAccessW;
    easize              : integer;
    pACL                : Windows.PACL;
begin
    ExplicitAccess[0].grfAccessPermissions:= STANDARD_RIGHTS_ALL or SPECIFIC_RIGHTS_ALL;
    ExplicitAccess[0].grfAccessMode:=Ord(SET_ACCESS);
    ExplicitAccess[0].grfInheritance:=SUB_CONTAINERS_AND_OBJECTS_INHERIT;
    ExplicitAccess[0].Trustee.TrusteeForm:=Ord(TRUSTEE_IS_NAME);
    ExplicitAccess[0].Trustee.TrusteeType:=Ord(TRUSTEE_IS_USER);
    ExplicitAccess[0].Trustee.ptstrName:='Everyone';//Access for all users
    SetEntriesinAclW(1,@ExplicitAccess,nil,pACL);//creates a new access control list

    //SecurityDescriptor:= AllocMem(Sizeof(SECURITY_DESCRIPTOR_MIN_LENGTH));
    SecurityDescriptor:= AllocMem(SECURITY_DESCRIPTOR_MIN_LENGTH);
    InitializeSecurityDescriptor(SecurityDescriptor,SECURITY_DESCRIPTOR_REVISION);
    SetSecurityDescriptorDacl(SecurityDescriptor,true,pacl,false);//sets information in a discretionary access control list (DACL).

    FillChar(SecurityAttributes,sizeof(SECURITY_ATTRIBUTES),#0);
    SecurityAttributes.nLength:=sizeof(SECURITY_ATTRIBUTES);
    SecurityAttributes.lpSecurityDescriptor:=SecurityDescriptor;
    SecurityAttributes.bInheritHandle:=false;
    CreateDirectory(PChar(NewDirectory),@SecurityAttributes);
    Result:=GetLastError=0;// if all ok, GetLastError = 0
end;

begin
  if CreateDirectoryFullAccess('C:\MyNewDir') then
   Writeln('Ok')
  else
   Writeln('Failed');

  Readln;
end.

推荐阅读
Life一切安好
这个屌丝很懒,什么也没留下!
DevBox开发工具箱 | 专业的在线开发工具网站    京公网安备 11010802040832号  |  京ICP备19059560号-6
Copyright © 1998 - 2020 DevBox.CN. All Rights Reserved devBox.cn 开发工具箱 版权所有