Option Explicit
Private Declare PtrSafe Function GetFileSecurity Lib "advapi32.dll" _
Alias "GetFileSecurityA" ( _
ByVal lpFileName As String, _
ByVal RequestedInformation As Long, _
pSecurityDescriptor As Byte, _
ByVal nLength As Long, _
lpnLengthNeeded As Long _
) As Long
Private Declare PtrSafe Function GetSecurityDescriptorOwner Lib "advapi32.dll" _
(pSecurityDescriptor As Any, _
pOwner As LongLong, _
lpbOwnerDefaulted As Long) As Long
Private Declare PtrSafe Function LookupAccountSid Lib "advapi32.dll" _
Alias "LookupAccountSidA" ( _
ByVal lpSystemName As String, _
ByVal Sid As LongLong, _
ByVal name As String, _
cbName As Long, _
ByVal ReferencedDomainName As String, _
cbReferencedDomainName As Long, _
peUse As Long) As Long
Private Const OWNER_SECURITY_INFORMATION = &H1
Private Const ERROR_INSUFFICIENT_BUFFER = 122&
Function GetFileOwner(ByVal szfilename As String) As String
Dim bSuccess As Long
Dim sizeSD As Long
Dim pOwner As LongLong
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 = GetFileSecurity( _
szfilename, _
OWNER_SECURITY_INFORMATION, _
0, _
0&, _
sizeSD)
If (bSuccess = 0) And _
(Err.LastDllError <> ERROR_INSUFFICIENT_BUFFER) Then
MsgBox "GetLastError returned : " & Err.LastDllError
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
MsgBox "GetLastError returned : " & Err.LastDllError
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
MsgBox "GetLastError returned : " & Err.LastDllError
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
MsgBox "GetLastError returned : " & Err.LastDllError
Exit Function
End If
GetFileOwner = name
End If
End Function