Jon*_*n B 5 vbscript wsh filesystemobject
我正在编写一个VB脚本来更新网络上的一些文件.在开始之前,我想知道是否有任何文件被锁定.在我真正做任何更新之前,我想这样做.
我知道当我尝试更换文件时,如果文件被锁定,我可以处理错误,但我真的想知道在开始更新任何文件之前是否有任何文件被锁定.
有没有办法看到使用VBS锁定文件(除了尝试替换它)?
Dav*_*dRR 11
此功能确定是否可以在"写入"模式下访问感兴趣的文件.这与确定文件是否被进程锁定不完全相同.不过,您可能会发现它适用于您的情况.(至少在出现更好的情况之前.)
此函数将指示当另一个进程锁定文件时无法进行"写入"访问.但是,它无法将该条件与阻止"写入"访问的其他条件区分开来.例如,如果文件的只读位设置或具有限制性NTFS权限,则也无法进行"写入"访问.当进行"写入"访问尝试时,所有这些条件都将导致"拒绝许可".
另请注意,如果某个文件被另一个进程锁定,则此函数返回的答案仅在执行该函数时才可靠.因此,并发问题是可能的.
如果发现以下任何条件,则抛出异常:"找不到文件","找不到路径"或"非法文件名"("错误的文件名或编号").
Function IsWriteAccessible(sFilePath)
' Strategy: Attempt to open the specified file in 'append' mode.
' Does not appear to change the 'modified' date on the file.
' Works with binary files as well as text files.
' Only 'ForAppending' is needed here. Define these constants
' outside of this function if you need them elsewhere in
' your source file.
Const ForReading = 1, ForWriting = 2, ForAppending = 8
IsWriteAccessible = False
Dim oFso : Set oFso = CreateObject("Scripting.FileSystemObject")
On Error Resume Next
Dim nErr : nErr = 0
Dim sDesc : sDesc = ""
Dim oFile : Set oFile = oFso.OpenTextFile(sFilePath, ForAppending)
If Err.Number = 0 Then
oFile.Close
If Err Then
nErr = Err.Number
sDesc = Err.Description
Else
IsWriteAccessible = True
End if
Else
Select Case Err.Number
Case 70
' Permission denied because:
' - file is open by another process
' - read-only bit is set on file, *or*
' - NTFS Access Control List settings (ACLs) on file
' prevents access
Case Else
' 52 - Bad file name or number
' 53 - File not found
' 76 - Path not found
nErr = Err.Number
sDesc = Err.Description
End Select
End If
' The following two statements are superfluous. The VB6 garbage
' collector will free 'oFile' and 'oFso' when this function completes
' and they go out of scope. See Eric Lippert's article for more:
' http://blogs.msdn.com/b/ericlippert/archive/2004/04/28/when-are-you-required-to-set-objects-to-nothing.aspx
'Set oFile = Nothing
'Set oFso = Nothing
On Error GoTo 0
If nErr Then
Err.Raise nErr, , sDesc
End If
End Function
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
24175 次 |
| 最近记录: |