This sample article will show you how to get owner of a file/folder and how to take ownership of a file/folder?
Step-By-Step Example
- Create a standard exe project - Add one module - Add one textbox and one command button on the form1 - Add one ListView control on the form1. To add ListView control you need to add reference to Microsoft Windows Common Control 5.0 (Click Project->Components) - Place the following code in form1 code window
Form1.frm |
Click here to copy the following block | Private Sub Command1_Click() On Error GoTo errHandler
ret = TakeOwnership(ListView1.SelectedItem.Text) If ret = 0 Then LoadListView Else MsgBox GetErrorMsg(Err.LastDllError) End If
Exit Sub errHandler: MsgBox Err.Description End Sub
Private Sub Form_Load() Text1 = "C:\" Command1.Caption = "Take Ownership of selected file" Call LoadListView End Sub Sub LoadListView() Dim i As Integer Dim full_path As String Dim itmX As ListItem ListView1.ListItems.Clear ListView1.ColumnHeaders.Clear
ChDir Text1 file_name = Dir(Text1)
With ListView1 .View = lvwReport
.ColumnHeaders.Add , , "File", ListView1.Width / 2 .ColumnHeaders.Add , , "Owner (User/Group)"
Do While file_name <> "" full_path = AddSlash(Text1) & file_name
Set itmX = .ListItems.Add With itmX .Text = full_path .SubItems(1) = GetFileOwner(full_path) End With file_name = Dir$ Loop End With End Sub Function AddSlash(fPath As String) As String If Right$(fPath, 1) = "\" Then AddSlash = fPath Else AddSlash = fPath & "\" End If End Function |
Add the folloing code in Module1
Module1.bas |
Click here to copy the following block | Option Explicit Option Base 0
Type ACE_HEADER AceType As Byte AceFlags As Byte AceSize As Long End Type
Type ACL AclRevision As Byte Sbz1 As Byte AclSize As Integer AceCount As Integer Sbz2 As Integer End Type
Type ACL_REVISION_INFORMATION AclRevision As Long End Type
Type ACL_SIZE_INFORMATION AceCount As Long AclBytesInUse As Long AclBytesFree As Long End Type
Type SECURITY_ATTRIBUTES nLength As Long lpSecurityDescriptor As Long bInheritHandle As Boolean End Type
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
Type SECURITY_QUALITY_OF_SERVICE Length As Long Impersonationlevel As Integer ContextTrackingMode As Integer EffectiveOnly As Boolean End Type
Type SID_AND_ATTRIBUTES Sid As Long Attributes As Long End Type Type SID_IDENTIFIER_AUTHORITY Value(6) As Byte End Type
Type LUID lowpart As Long highpart As Long End Type
Type LUID_AND_ATTRIBUTES pLuid As LUID Attributes As Long End Type
Public Const ANYSIZE_ARRAY = 1
Type TOKEN_GROUPS GroupCount As Long Groups(ANYSIZE_ARRAY) As SID_AND_ATTRIBUTES End Type
Type TOKEN_PRIVILEGES PrivilegeCount As Long Privileges(ANYSIZE_ARRAY) As LUID_AND_ATTRIBUTES End Type
Type LARGE_INTEGER lowpart As Long highpart As Long End Type
Enum SE_OBJECT_TYPE SE_UNKNOWN_OBJECT_TYPE = 0& SE_FILE_OBJECT SE_SERVICE SE_PRINTER SE_REGISTRY_KEY SE_LMSHARE SE_KERNEL_OBJECT SE_WINDOW_OBJECT End Enum
Declare Function SetSecurityDescriptorSacl Lib "advapi32.dll" _ (pSecurityDescriptor As Any, _ ByVal bSaclPresent As Long, _ pSacl As ACL, _ ByVal bSaclDefaulted As Long) As Long
Declare Function InitializeSecurityDescriptor Lib "advapi32.dll" _ (pSecurityDescriptor As Any, _ ByVal dwRevision As Long) As Long
Declare Function SetFileSecurity Lib "advapi32.dll" Alias "SetFileSecurityA" _ (ByVal lpFileName As String, _ ByVal SecurityInformation As Long, _ pSecurityDescriptor As Any) As Long
Declare Function GetFileSecurity Lib "advapi32.dll" Alias "GetFileSecurityA" _ (ByVal lpFileName As String, _ ByVal RequestedInformation As Long, _ pSecurityDescriptor As Any, _ ByVal nLength As Long, _ lpnLengthNeeded As Long) As Long
Declare Function AllocateAndInitializeSid Lib "advapi32.dll" _ (pIdentifierAuthority As SID_IDENTIFIER_AUTHORITY, _ ByVal nSubAuthorityCount As Byte, _ ByVal nSubAuthority0 As Long, _ ByVal nSubAuthority1 As Long, _ ByVal nSubAuthority2 As Long, _ ByVal nSubAuthority3 As Long, _ ByVal nSubAuthority4 As Long, _ ByVal nSubAuthority5 As Long, _ ByVal nSubAuthority6 As Long, _ ByVal nSubAuthority7 As Long, _ lpPSid As Long) As Long
Declare Function SetSecurityDescriptorDacl Lib "advapi32.dll" _ (pSecurityDescriptor As Any, _ ByVal bDaclPresent As Long, _ pDacl As Any, _ ByVal bDaclDefaulted As Long) As Long
Declare Function SetSecurityDescriptorDaclNul Lib "advapi32.dll" Alias "SetSecurityDescriptorDacl" _ (pSecurityDescriptor As Any, _ ByVal bDaclPresent As Long, _ ByVal pDacl As Long, _ ByVal bDaclDefaulted As Long) As Long
Declare Function SetSecurityDescriptorGroup Lib "advapi32.dll" _ (pSecurityDescriptor As Any, _ pGroup As Any, _ ByVal bGroupDefaulted As Long) As Long
Declare Function SetSecurityDescriptorOwner Lib "advapi32.dll" _ (pSecurityDescriptor As Any, _ pOwner As Any, _ ByVal bOwnerDefaulted As Long) As Long
Declare Function SetSecurityDescriptorOwnerPtr Lib "advapi32.dll" Alias "SetSecurityDescriptorOwner" _ (pSecurityDescriptor As Any, _ ByVal pOwner As Any, _ ByVal bOwnerDefaulted As Long) As Long
Declare Function GetAce Lib "advapi32.dll" _ (pAcl As ACL, _ ByVal dwAceIndex As Long, _ pAce As Any) As Long
Declare Function GetAclInformation Lib "advapi32.dll" _ (pAcl As ACL, _ pAclInformation As Any, _ ByVal nAclInformationLength As Long, _ ByVal dwAclInformationClass As Integer) As Long
Declare Function GetLengthSid Lib "advapi32.dll" _ (pSid As Any) As Long
Declare Function GetSidIdentifierAuthority Lib "advapi32.dll" _ (pSid As Any) As SID_IDENTIFIER_AUTHORITY
Declare Function GetSidLengthRequired Lib "advapi32.dll" _ (ByVal nSubAuthorityCount As Byte) As Long
Declare Function GetSidSubAuthority Lib "advapi32.dll" _ (pSid As Any, _ ByVal nSubAuthority As Long) As Long
Declare Function GetSidSubAuthorityCount Lib "advapi32.dll" _ (pSid As Any) As Byte
Declare Sub FreeSid Lib "advapi32.dll" (pSid As Any) Declare Function OpenProcessToken Lib "advapi32.dll" _ (ByVal ProcessHandle As Long, _ ByVal DesiredAccess As Long, _ TokenHandle As Long) As Long
Declare Function GetCurrentProcess Lib "kernel32" () As Long
Declare Function GetCurrentProcessId Lib "kernel32" () As Long
Declare Function LookupPrivilegeValue Lib "advapi32.dll" Alias "LookupPrivilegeValueA" _ (ByVal lpSystemName As String, _ ByVal lpName As String, _ lpLuid As LUID) As Long
Declare Function LookupPrivilegeName Lib "advapi32.dll" Alias "LookupPrivilegeNameA" _ (ByVal lpSystemName As String, _ lpLuid As LARGE_INTEGER, _ ByVal lpName As String, _ cbName As Long) As Long
Declare Function LookupPrivilegeDisplayName Lib "advapi32.dll" Alias "LookupPrivilegeDisplayNameA" _ (ByVal lpSystemName As String, _ ByVal lpName As String, _ ByVal lpDisplayName As String, _ cbDisplayName As Long, _ lpLanguageID As Long) As Long
Declare Function AdjustTokenPrivileges Lib "advapi32.dll" _ (ByVal TokenHandle As Long, _ ByVal DisableAllPrivileges As Long, _ NewState As Any, _ ByVal BufferLength As Long, _ ByVal PreviousState As Long, _ ByVal ReturnLength As Long) As Long
Declare Function AdjustTokenGroups Lib "advapi32.dll" _ (ByVal TokenHandle As Long, _ ByVal ResetToDefault As Long, _ NewState As TOKEN_GROUPS, _ ByVal BufferLength As Long, _ PreviousState As TOKEN_GROUPS, _ ReturnLength As Long) As Long
Declare Function GetVersion Lib "kernel32" () As Long
Declare Function GetNamedSecurityInfo Lib "advapi32.dll" Alias "GetNamedSecurityInfoA" ( _ ByVal pObjectName As String, _ ByVal ObjectType As SE_OBJECT_TYPE, _ ByVal SecurityInfo As Long, _ ppsidOwner As Long, _ ppsidGroup As Long, _ ppDacl As Long, _ ppSacl As Long, _ ppSecurityDescriptor As Long) As Long
Declare Function SetNamedSecurityInfo Lib "advapi32.dll" Alias "SetNamedSecurityInfoA" ( _ ByVal pObjectName As String, _ ByVal ObjectType As SE_OBJECT_TYPE, _ ByVal SecurityInfo As Long, _ ByVal psidOwner As Long, _ ByVal psidGroup As Long, _ ByVal pDacl As Long, _ ByVal pSacl As Long) As Long
Declare Function GetLastError Lib "kernel32" () As Long
Declare Function FormatMessage Lib "kernel32" Alias "FormatMessageA" _ (ByVal dwFlags As Long, _ lpSource As Any, _ ByVal dwMessageId As Long, _ ByVal dwLanguageId As Long, _ ByVal lpBuffer As String, _ ByVal nSize As Long, _ Arguments As Long) As Long
Public Const ACCESS_ALLOWED_ACE_TYPE = &H0 Public Const ACCESS_DENIED_ACE_TYPE = &H1 Public Const ACCESS_SYSTEM_SECURITY = &H1000000 Public Const ACL_REVISION = (2) Public Const ACL_REVISION1 = (1) Public Const ACL_REVISION2 = (2) Public Const AclRevisionInformation = 1 Public Const AclSizeInformation = 2 Public Const SECURITY_ANONYMOUS_LOGON_RID = &H7 Public Const SECURITY_BATCH_RID = &H3 Public Const SECURITY_BUILTIN_DOMAIN_RID = &H20 Public Const SECURITY_CONTEXT_TRACKING = &H40000 Public Const SECURITY_CREATOR_GROUP_RID = &H1 Public Const SECURITY_CREATOR_OWNER_RID = &H0 Public Const SECURITY_DESCRIPTOR_MIN_LENGTH = (20) Public Const SECURITY_DESCRIPTOR_REVISION = (1) Public Const SECURITY_DESCRIPTOR_REVISION1 = (1) Public Const SECURITY_EFFECTIVE_ONLY = &H80000 Public Const SECURITY_INTERACTIVE_RID = &H4 Public Const SECURITY_LOCAL_RID = &H0 Public Const SECURITY_LOCAL_SYSTEM_RID = &H12 Public Const SECURITY_LOGON_IDS_RID = &H5 Public Const SECURITY_NETWORK_RID = &H2 Public Const SECURITY_NT_NON_UNIQUE = &H15 Public Const SECURITY_NULL_RID = &H0 Public Const SECURITY_SERVICE_RID = &H6 Public Const SECURITY_SQOS_PRESENT = &H100000 Public Const SECURITY_VALID_SQOS_FLAGS = &H1F0000 Public Const SECURITY_WORLD_RID = &H0 Public Const SecurityAnonymous = 1 Public Const SecurityIdentification = 2 Public Const SECURITY_NULL_SID_AUTHORITY = 0 Public Const SECURITY_WORLD_SID_AUTHORITY = 1 Public Const SECURITY_LOCAL_SID_AUTHORITY = 2 Public Const SECURITY_CREATOR_SID_AUTHORITY = 3 Public Const SECURITY_NT_AUTHORITY As Long = 5& Public Const DACL_SECURITY_INFORMATION As Long = &H4 Public Const DOMAIN_ALIAS_RID_ACCOUNT_OPS = &H224 Public Const DOMAIN_ALIAS_RID_ADMINS = &H220 Public Const DOMAIN_ALIAS_RID_BACKUP_OPS = &H227 Public Const DOMAIN_ALIAS_RID_GUESTS = &H222 Public Const DOMAIN_ALIAS_RID_POWER_USERS = &H223 Public Const DOMAIN_ALIAS_RID_PRINT_OPS = &H226 Public Const DOMAIN_ALIAS_RID_REPLICATOR = &H228 Public Const DOMAIN_ALIAS_RID_SYSTEM_OPS = &H225 Public Const DOMAIN_ALIAS_RID_USERS = &H221 Public Const DOMAIN_GROUP_RID_ADMINS = &H200 Public Const DOMAIN_GROUP_RID_GUESTS = &H202 Public Const DOMAIN_GROUP_RID_USERS = &H201 Public Const DOMAIN_USER_RID_ADMIN = &H1F4 Public Const DOMAIN_USER_RID_GUEST = &H1F5 Public Const SE_TAKE_OWNERSHIP_NAME = "SeTakeOwnershipPrivilege" & vbNullChar
Public Const SE_PRIVILEGE_ENABLED = &H2 Public Const ERROR_SUCCESS = 0& Public Const TOKEN_ADJUST_PRIVILEGES = &H20 Public Const TOKEN_QUERY = &H8 Public Const OWNER_SECURITY_INFORMATION As Long = &H1& Public Const FORMAT_MESSAGE_ALLOCATE_BUFFER = &H100 Public Const FORMAT_MESSAGE_ARGUMENT_ARRAY = &H2000 Public Const FORMAT_MESSAGE_FROM_HMODULE = &H800 Public Const FORMAT_MESSAGE_FROM_STRING = &H400 Public Const FORMAT_MESSAGE_FROM_SYSTEM = &H1000 Public Const FORMAT_MESSAGE_IGNORE_INSERTS = &H200 Public Const FORMAT_MESSAGE_MAX_WIDTH_MASK = &HFF Public Const LANG_USER_DEFAULT = &H400&
Private Declare Function GetSecurityDescriptorOwner Lib "advapi32.dll" _ (pSecurityDescriptor As Any, _ pOwner As Long, _ lpbOwnerDefaulted As Long) As Long
Private Declare Function LookupAccountSid Lib "advapi32.dll" _ Alias "LookupAccountSidA" ( _ ByVal lpSystemName As String, _ ByVal Sid As Long, _ ByVal name As String, _ cbName As Long, _ ByVal ReferencedDomainName As String, _ cbReferencedDomainName As Long, _ peUse As Long) As Long
Private Declare Function GetWindowsDirectory Lib "kernel32" _ Alias "GetWindowsDirectoryA" ( _ ByVal lpBuffer As String, _ ByVal nSize As Long) As Long
Private Const ERROR_INSUFFICIENT_BUFFER = 122& Private Const MAX_PATH = 255
Function AssertTakeOwnership(fEnable As Integer) As Integer Dim hToken As Long Dim TakeOwnershipValue As LUID Dim tkp As TOKEN_PRIVILEGES Dim result As Long Dim NulStr As String
NulStr = Chr$(0)
result = OpenProcessToken(GetCurrentProcess(), TOKEN_ADJUST_PRIVILEGES Or TOKEN_QUERY, hToken) If fEnable Then result = LookupPrivilegeValue(NulStr, _ SE_TAKE_OWNERSHIP_NAME, _ TakeOwnershipValue) If result = False Then AssertTakeOwnership = False End If
tkp.PrivilegeCount = 1 tkp.Privileges(0).pLuid = TakeOwnershipValue tkp.Privileges(0).Attributes = SE_PRIVILEGE_ENABLED
result = AdjustTokenPrivileges(hToken, _ False, _ tkp, _ Len(tkp), _ 0&, _ 0&)
If (GetLastError() <> ERROR_SUCCESS) Then AssertTakeOwnership = False Else AssertTakeOwnership = True End If Else result = AdjustTokenPrivileges(hToken, _ &HFFFF, _ 0&, _ 0&, _ 0&, _ 0&)
If (GetLastError() <> ERROR_SUCCESS) Then AssertTakeOwnership = False End If End If End Function
Function OSIsNT() As Long
Dim lngVersion As Long
lngVersion = GetVersion()
If ((lngVersion And &H80000000) = 0) Then OSIsNT = True Else OSIsNT = False End If
End Function
Public Function TakeOwnership(FilePath As String) As Long
Dim pSIDAliasAdmins As Long Dim result As Long, result2 As Long pSIDAliasAdmins = 0&
Dim PACLptr As Long PACLptr = 0&
Dim NulStr As String Dim sd As Long Dim Lneed As Long
NulStr = Chr$(0)
Dim siaNTAuthority As SID_IDENTIFIER_AUTHORITY siaNTAuthority.Value(5) = SECURITY_NT_AUTHORITY
result = InitializeSecurityDescriptor(sd, SECURITY_DESCRIPTOR_REVISION) If result = 0 Then TakeOwnership = -1 Exit Function End If
result = SetSecurityDescriptorDaclNul(sd, -1&, 0&, 0&) If result = 0 Then TakeOwnership = -1 Exit Function End If
result = AllocateAndInitializeSid(siaNTAuthority, 2, SECURITY_BUILTIN_DOMAIN_RID, DOMAIN_ALIAS_RID_ADMINS, _ 0&, 0&, 0&, 0&, 0&, 0&, pSIDAliasAdmins) If result = False Then TakeOwnership = -1 Exit Function End If
result = SetNamedSecurityInfo( _ FilePath & vbNullChar, _ SE_FILE_OBJECT, _ OWNER_SECURITY_INFORMATION, _ pSIDAliasAdmins, _ 0&, _ 0&, _ 0&)
If result <> 0 Then TakeOwnership = result FreeSid (pSIDAliasAdmins) Exit Function End If
result = SetFileSecurity(FilePath & vbNullChar, DACL_SECURITY_INFORMATION, sd) If result = 1 Then TakeOwnership = 0 Else TakeOwnership = 5 End If FreeSid (pSIDAliasAdmins) End Function
Public Function GetFileOwner(Optional strPath As String) As String Dim szfilename As String Dim bSuccess As Long Dim sizeSD As Long Dim pOwner As Long Dim name As String Dim domain_name As String Dim name_len As Long Dim domain_len As Long Dim sdBuf() As Byte Dim nLength As Long Dim deUse As Long
bSuccess = 0 name = "" domain_name = "" name_len = 0 domain_len = 0 pOwner = 0
szfilename = strPath name_len = Len(szfilename)
bSuccess = GetFileSecurity( _ szfilename, _ OWNER_SECURITY_INFORMATION, _ 0, _ 0&, _ sizeSD)
If (bSuccess = 0) And _ (Err.LastDllError <> ERROR_INSUFFICIENT_BUFFER) Then If Err.LastDllError = 1332 Then GetFileOwner = "{UNKNOWN}" Exit Function End If
ReDim sdBuf(0 To sizeSD - 1) As Byte
bSuccess = GetFileSecurity( _ szfilename, _ OWNER_SECURITY_INFORMATION, _ sdBuf(0), _ sizeSD, _ sizeSD)
If (bSuccess <> 0) Then
bSuccess = GetSecurityDescriptorOwner(sdBuf(0), pOwner, 0&) If (bSuccess = 0) Then If Err.LastDllError = 1332 Then GetFileOwner = "{UNKNOWN}" Exit Function End If
bSuccess = LookupAccountSid(vbNullString, pOwner, name, name_len, _ domain_name, domain_len, deUse) If (bSuccess = 0) And _ (Err.LastDllError <> ERROR_INSUFFICIENT_BUFFER) Then If Err.LastDllError = 1332 Then GetFileOwner = "{UNKNOWN}" Exit Function End If
name = Space(name_len - 1) domain_name = Space(domain_len - 1)
bSuccess = LookupAccountSid(vbNullString, pOwner, name, name_len, _ domain_name, domain_len, deUse) If bSuccess = 0 Then End If
GetFileOwner = name End If End Function
Function GetErrorMsg(ByVal dwErrCode As Long) As String Static sMsgBuf As String * 257, dwLen As Long
dwLen = FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM _ Or FORMAT_MESSAGE_IGNORE_INSERTS _ Or FORMAT_MESSAGE_MAX_WIDTH_MASK, ByVal 0&, _ dwErrCode, LANG_USER_DEFAULT, _ ByVal sMsgBuf, 256&, 0&)
If dwLen > 0 Then GetErrorMsg = Left$(sMsgBuf, dwLen) Else GetErrorMsg = "Unknown error message" End If End Function |
- Now Press F5 to run the project - Select any file and click on the command button to take the Ownership of selected file
After you press command button ListView should refresh the owner of the file. |
|