获取SecurityDescriptor参数

问题描述 投票:0回答:1

我正在寻找一个函数来查找锁定文件的用户名。

我发现这个效果很好:

Function GetUsername(fileDir As String, fileName As String) As String

'On Error Resume Next
Dim secUtil As Object
Dim secDesc As Object

Set secUtil = CreateObject("ADsSecurityUtility")
Set secDesc = secUtil.GetSecurityDescriptor(fileDir & fileName, 1, 1)

GetUsername = secDesc.Owner

End Function

我想改变

Set secDesc = secUtil.GetSecurityDescriptor(fileDir & fileName, 1, 1)

为了

Set secDesc = secUtil.GetSecurityDescriptor(fullFileName, 1, 1)

我在函数声明中进行了所需的更改,甚至在没有任何函数的情况下进行了尝试,但无法使该方法与包含完整路径的唯一变量一起使用,迫使我出于我不明白的原因将其拆分。

这是完整的功能(我希望翻译得很好)

Function GetUsername(fileDir As String, fileName As String) As 
String 'case 1
'Function GetUsername(fullFileName As String) As String 'case 2

Dim secUtil As Object
Dim secDesc As Object

Set secUtil = CreateObject("ADsSecurityUtility")
Set secDesc = secUtil.GetSecurityDescriptor(fileDir & fileName, 1, 1) 'case 1
'Set secDesc = secUtil.GetSecurityDescriptor(fullFileName, 1, 1) 'case 2

GetUsername = secDesc.Owner

End Function


Function IsOpen(file As String) As Boolean

Dim filenum As Integer, errnum As Integer

On Error Resume Next
filenum = FreeFile()

Open file For Input Lock Read As #filenum
Close filenum
errnum = Err
On Error GoTo 0

Select Case errnum
    Case 0
        IsOpen = False
    Case 70
        IsOpen = True
    Case Else
        Error errnum
End Select
End Function


Function CheckFile(file As String) As Boolean

'existence test
Set fs = CreateObject("Scripting.FileSystemObject")

If fs.fileexists(file) = True Then 'the file exists
    If IsOpen(file) = True Then 'the file is open
        MsgBox "file opened" & Chr(10) & "By : " & GetUsername("R\", "TEST.xlsx") 'case 1 : works
        'MsgBox "file opened" & Chr(10) & "By : " & GetUsername(file) 'case 2 : don't works
    Else
        MsgBox "closed file"
    End If
Else
    MsgBox "ERROR: The file does not exists"
End If

End Function


Private Sub TestOpen()

Dim ftest As String

ftest = "R:\TEST.xlsx"

CheckFile (ftest)

End Sub
vba file-locking
1个回答
0
投票

GetSecurityDescriptor

文档
似乎相当强调第一个参数必须是变体。

一个 VARIANT 字符串,其中包含要检索的对象的路径 安全描述符。

我尝试了你修改后的代码,果然它不起作用。然而,在进行一个小的更改以强制参数改变后,代码工作得很好。

Set secDesc = secUtil.GetSecurityDescriptor(CVar(fullFileName), 1, 1)

那么从你的问题来看,情况1和情况2有什么区别?我不知道。但似乎串联的结果一定是一个变体,这就是案例 1 起作用的原因。

© www.soinside.com 2019 - 2024. All rights reserved.