如何使用win32 api将文件所有权转让给当前用户

我想使用win32 api获取文件所有权,我希望我的代码可以在xp和win7上运行

无论如何,这就是我想出的

更改文件所有权的函数

int ChangeFileOwner() { HANDLE token; char *filename = "c:\\file1.txt"; //(not owned by the current user) DWORD len; PSECURITY_DESCRIPTOR security = NULL; int retValue = 1; PSID sid; // Get the privileges you need if (OpenProcessToken(GetCurrentProcess(), TOKEN_ALL_ACCESS, &token)) { if(!SetPrivilege("SeTakeOwnershipPrivilege", 1))retValue=0; if(!SetPrivilege("SeSecurityPrivilege", 1))retValue=0; if(!SetPrivilege("SeBackupPrivilege", 1))retValue=0; if(!SetPrivilege("SeRestorePrivilege", 1))retValue=0; } else retValue = 0; // Create the security descriptor if (retValue) { GetFileSecurity(filename, OWNER_SECURITY_INFORMATION, security, 0, &len); security = (PSECURITY_DESCRIPTOR)malloc(len); if (!InitializeSecurityDescriptor(security,SECURITY_DESCRIPTOR_REVISION)) retValue = 0; } // Get the sid for the username if (retValue) { GetLogonSID(token, &sid) ; } // Set the sid to be the new owner if (retValue && !SetSecurityDescriptorOwner(security, sid, 0)) retValue = 0; // Save the security descriptor if (retValue) retValue = SetFileSecurity(filename, OWNER_SECURITY_INFORMATION, security); if (security) free(security); return retValue; } 

获取当前用户SID的函数

 BOOL GetLogonSID (HANDLE hToken, PSID *ppsid) { BOOL bSuccess = FALSE; DWORD dwIndex; DWORD dwLength = 0; PTOKEN_GROUPS ptg = NULL; // Get required buffer size and allocate the TOKEN_GROUPS buffer. GetTokenInformation(hToken,TokenGroups,(LPVOID) ptg,0,&dwLength) ; ptg = (PTOKEN_GROUPS)HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, dwLength); // Get the token group information from the access token. GetTokenInformation(hToken,TokenGroups,(LPVOID) ptg,dwLength,&dwLength) ; // Loop through the groups to find the logon SID. for (dwIndex = 0; dwIndex GroupCount; dwIndex++) if ((ptg->Groups[dwIndex].Attributes & SE_GROUP_LOGON_ID) == SE_GROUP_LOGON_ID) { // Found the logon SID; make a copy of it. dwLength = GetLengthSid(ptg->Groups[dwIndex].Sid); *ppsid = (PSID) HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, dwLength); CopySid(dwLength, *ppsid, ptg->Groups[dwIndex].Sid); break; } return TRUE; } 

代码设置权限

 int SetPrivilege(char *privilege, int enable) { TOKEN_PRIVILEGES tp; LUID luid; HANDLE token; if (!OpenProcessToken(GetCurrentProcess(), TOKEN_ADJUST_PRIVILEGES, &token)) return 0; if (!LookupPrivilegeValue(NULL, privilege, &luid)) return 0; tp.PrivilegeCount = 1; tp.Privileges[0].Luid = luid; if (enable) tp.Privileges[0].Attributes = SE_PRIVILEGE_ENABLED; else tp.Privileges[0].Attributes = 0; // Enable the privilege or disable all privileges. return AdjustTokenPrivileges(token, 0, &tp, NULL, NULL, NULL); } 

Interesting Posts