b = InitializeSecurityDescriptor(pSD,SECURITY_DESCRIPTOR_REVISION); if(!b) DbgOut("Security Descriptor initialization failed");
// Add the ACL to the security descriptor. c = SetSecurityDescriptorDacl(pSD, TRUE, // bDaclPresent flag pACL, FALSE); // not a default DACL if(!c) DbgOut("SetSecurityDescriptorDacl failed");
//Change the security attributes // d = SetFileSecurity(FileName, DACL_SECURITY_INFORMATION, pSD); SetNamedSecurityInfo(L"C:\\Program Files\\Mydir\\My.log",SE_FILE_OBJECT,DACL_SECURITY_INFORMATION,pSD,NULL,NULL,NULL); if(d != ERROR_SUCCESS) DbgOut("SetFileSecurity failed"); if (pEveryoneSID) FreeSid(pEveryoneSID); if (pACL) LocalFree(pACL); if (pSD) LocalFree(pSD); }
void SetFilePermission(LPCTSTR FileName)
{
PSID pEveryoneSID = NULL;
BOOL a= TRUE;
BOOL b= TRUE;
BOOL c= TRUE;
DWORD d= 0;
DWORD ret = 0;
PACL pACL = NULL;
EXPLICIT_ACCESS ea[1];
SID_IDENTIFIER_AUTHORITY SIDAuthWorld = SECURITY_WORLD_SID_AUTHORITY;
// Create a well-known SID for the Everyone group.
a = AllocateAndInitializeSid(&SIDAuthWorld, 1,
SECURITY_WORLD_RID,
0, 0, 0, 0, 0, 0, 0,
&pEveryoneSID);
if(!a)
DbgOut("SID initialization failed");
// Initialize an EXPLICIT_ACCESS structure for an ACE.
// The ACE will allow Everyone read access to the key.
ZeroMemory(&ea, 1 * sizeof(EXPLICIT_ACCESS));
ea[0].grfAccessPermissions = 0xFFFFFFFF;
ea[0].grfAccessMode = GRANT_ACCESS;
ea[0].grfInheritance= NO_INHERITANCE;
ea[0].Trustee.TrusteeForm = TRUSTEE_IS_SID;
ea[0].Trustee.TrusteeType = TRUSTEE_IS_WELL_KNOWN_GROUP;
ea[0].Trustee.ptstrName = (LPTSTR) pEveryoneSID;
// Create a new ACL that contains the new ACEs.
ret = SetEntriesInAcl(1, ea, NULL, &pACL); if(ret != ERROR_SUCCESS)
DbgOut("ACL entry failed");
// Initialize a security descriptor.
PSECURITY_DESCRIPTOR pSD = (PSECURITY_DESCRIPTOR) LocalAlloc(LPTR,
SECURITY_DESCRIPTOR_MIN_LENGTH);
b = InitializeSecurityDescriptor(pSD,SECURITY_DESCRIPTOR_REVISION);
if(!b)
DbgOut("Security Descriptor initialization failed");
// Add the ACL to the security descriptor.
c = SetSecurityDescriptorDacl(pSD,
TRUE, // bDaclPresent flag
pACL,
FALSE); // not a default DACL
if(!c)
DbgOut("SetSecurityDescriptorDacl failed");
//Change the security attributes
// d = SetFileSecurity(FileName, DACL_SECURITY_INFORMATION, pSD);
SetNamedSecurityInfo(L"C:\\Program Files\\Mydir\\My.log",SE_FILE_OBJECT,DACL_SECURITY_INFORMATION,pSD,NULL,NULL,NULL);
if(d != ERROR_SUCCESS)
DbgOut("SetFileSecurity failed");
if (pEveryoneSID)
FreeSid(pEveryoneSID);
if (pACL)
LocalFree(pACL);
if (pSD)
LocalFree(pSD);
}
http://msdn.microsoft.com/zh-cn/library/system.security.accesscontrol.directorysecurity(v=vs.80).aspx
DirectorySecurity sec = new DirectorySecurity();
FileSystemAccessRule rule = new FileSystemAccessRule("administrator", FileSystemRights.Delete, AccessControlType.Allow);
sec.AddAccessRule(rule);
Directory.CreateDirectory(@"f:\ccc", sec);
在f:\下创建ccc目录,给予administrator一个删除权限。你在msdn中查下相关这几个类和方法的说明。
FileSystemAccessRule 构造函数