概要
本文说明如何调用要更改所有权的文件或文件夹从 Microsoft Visual Basic 低级访问控制功能。
更多信息
如果用户被授予 SE_RESTORE_NAME 特权 (" 还原文件和目录 "), 用户更改安全文件系统上文件或文件夹的所有者。 默认情况下, Administrators 和 BackupOperators 保存 SE_RESTORE_NAME 特权。
除了要位于进程访问令牌, 还必须授予 SE_RESTORE_NAME 特权 (启用)。 您可以通过使用 AdjustTokenPrivileges() 函数授予此特权。 已授予特权, 后过程可设置任何有效用户或组 SID 作为所有者对文件或文件夹。
示例代码
以下示例 VisualBasic 代码演示如何授予 SE_RESTORE_NAME 权限, 然后设置文件或目录的所有者。 ChangeOwnerOfFile() 函数使用文件或文件夹名和用户名。 指定文件或文件夹的所有者它然后使指定用户。
注意 : 此代码仅当目标文件或文件夹, 位于安全文件系统如 NTFS, 才有用。 FAT 和 FAT 32 文件系统是不安全, 并且因此, 这些文件系统上文件没有所有者。
Option Explicit
'' Global constants we must use with security descriptor
Private Const SECURITY_DESCRIPTOR_REVISION = 1
Private Const OWNER_SECURITY_INFORMATION = 1&
'' Access Token constants
Private Const TOKEN_ASSIGN_PRIMARY = &H1
Private Const TOKEN_DUPLICATE = &H2
Private Const TOKEN_IMPERSONATE = &H4
Private Const TOKEN_QUERY = &H8
Private Const TOKEN_QUERY_SOURCE = &H10
Private Const TOKEN_ADJUST_PRIVILEGES = &H20
Private Const TOKEN_ADJUST_GROUPS = &H40
Private Const TOKEN_ADJUST_DEFAULT = &H80
Private Const TOKEN_ALL_ACCESS = TOKEN_ASSIGN_PRIMARY _
+ TOKEN_DUPLICATE + TOKEN_IMPERSONATE + TOKEN_QUERY _
+ TOKEN_QUERY_SOURCE + TOKEN_ADJUST_PRIVILEGES _
+ TOKEN_ADJUST_GROUPS + TOKEN_ADJUST_DEFAULT
Private Const ANYSIZE_ARRAY = 1
'' Token Privileges constants
Private Const SE_RESTORE_NAME = "SeRestorePrivilege"
Private Const SE_PRIVILEGE_ENABLED = 2&
'' ACL structure
Private Type ACL
AclRevision As Byte
Sbz1 As Byte
AclSize As Integer
AceCount As Integer
Sbz2 As Integer
End Type
Private Type SECURITY_DESCRIPTOR
Revision As Byte
Sbz1 As Byte
Control As Long
Owner As Long
Group As Long
Sacl As ACL
Dacl As ACL
End Type
'' Token structures
Private Type LARGE_INTEGER
lowpart As Long
highpart As Long
End Type
Private Type LUID
lowpart As Long
highpart As Long
End Type
Private Type LUID_AND_ATTRIBUTES
pLuid As LUID
Attributes As Long
End Type
Private Type TOKEN_PRIVILEGES
PrivilegeCount As Long
Privileges(ANYSIZE_ARRAY) As LUID_AND_ATTRIBUTES
End Type
'' Win32 API calls
Private Declare Function LookupAccountName Lib "advapi32.dll" _
Alias "LookupAccountNameA" (ByVal lpSystemName As String, _
ByVal lpAccountName As String, Sid As Byte, cbSid As Long, _
ByVal ReferencedDomainName As String, _
cbReferencedDomain