int
queryUserSIDToFile()
{
SECURITY_ATTRIBUTES sa;
/
/
和文件有关的安全结构
SECURITY_DESCRIPTOR sd;
/
/
声明一个SD
BYTE aclBuffer[
1024
];
/
/
buffer
PACL pacl
=
(PACL)&aclBuffer;
/
/
声明一个ACL,长度是
1024
BYTE sidBuffer[
100
];
/
/
sid
buffer
PSID psid
=
(PSID)&sidBuffer;
/
/
声明SID,长度是
100
DWORD sidBufferSize
=
100
;
DWORD domainBufferSize
=
80
;
TCHAR domainBuffer[
80
];
HANDLE hFile;
SID_NAME_USE snu;
/
/
初始化SD、初始化ACL
InitializeSecurityDescriptor(&sd, SECURITY_DESCRIPTOR_REVISION);
InitializeAcl(pacl,
1024
, ACL_REVISION);
TCHAR UserName[
256
]
=
{
0
};
DWORD dwSize_UserName
=
_countof(UserName);
/
/
获取用户名
GetUserName(UserName, &dwSize_UserName);
/
/
查询用户 sid
LookupAccountName(
0
, UserName, psid, &sidBufferSize, domainBuffer, &domainBufferSize, &snu);
/
/
设置该用户的Access
-
Allowed的ACE,其权限为
All
-
Access
SECURITY_INFORMATION info;
DWORD err
=
GetLastError();
AddAccessAllowedAce(pacl, ACL_REVISION, GENERIC_ALL, psid);
/
/
把ACL设置到SD中
SetSecurityDescriptorDacl(&sd, TRUE, pacl, FALSE);
/
/
把SD放到文件安全结构SA中
sa.nLength
=
sizeof(SECURITY_ATTRIBUTES);
sa.bInheritHandle
=
FALSE;
sa.lpSecurityDescriptor
=
&sd;
/
/
开始创建文件
hFile
=
CreateFile(L
"D://Test1.txt"
,
0
,
0
, &sa, CREATE_NEW, FILE_ATTRIBUTE_NORMAL,
0
);
if
(hFile
=
=
INVALID_HANDLE_VALUE)
{
DWORD derr
=
GetLastError();
MessageBox(NULL, L
"创建失败!"
, NULL, NULL);
return
-
1
;
}
MessageBox(NULL, L
"创建成功!"
, NULL, NULL);
CloseHandle(hFile);
return
0
;
}