打开前如何检查.txt文件的文件锁定

时间:2019-09-16 16:25:15

标签: excel vba file text locking

长话短说...我正在使用PC打开服务器上的.txt文件...但是有时.txt文件未完成(仍有数据存储在源计算机的缓冲区中)

FilePath = "D:\test.txt"

Workbooks.Open(Filename:=FilePath, ReadOnly:=True, IgnoreReadOnlyRecommended:=True)

比我聪明的人已经确定.txt文件已由操作系统“锁定”,直到完成为止,但我仍然可以打开它。我想等待.txt文件在打开之前被“未锁定”。我该怎么做?

注意:比我更聪明的人解释.... txt文件可以通过“记事本”之类的“笨拙”程序打开,但是如果您尝试使用“ Microsoft Word”打开它......收到一条消息,告诉您它已被锁定...

2 个答案:

答案 0 :(得分:0)

import time

is_open = False

while not(is_open):
    try:
        f = open('test.txt','w')
        is_open=True
    except:
        time.sleep(1)

答案 1 :(得分:0)

我不知道下面的代码将如何适合您的情况。

  • 您可以将常量更改为参数(如果您认为需要更改/动态确定其值)。
  • 您还可以更改GetFileOrWait的实现,使其允许无限循环(我选择避免这种情况,但也许您想要这样)。
  • 总而言之,以下基本上是一个试图在120秒内返回工作簿(或因错误而超时)的函数-您希望可以在父子例程/过程中使用该函数。
  • 您可以使用Timer或其他较低级别的API来指定更精细的频率(秒可能太粗糙)。

Option Explicit

Private Function GetFileOrNothing() As Workbook
    Const FILE_PATH As String = "D:\test.txt" ' Could pass this in as argument (if needed).
    On Error Resume Next
    Set GetFileOrNothing = Workbooks.Open(Filename:=FILE_PATH, ReadOnly:=True, IgnoreReadOnlyRecommended:=True)
    On Error GoTo 0
End Function

Private Function GetFileOrWait() As Workbook
    ' Attempts to open a file. If access fails, waits n seconds before trying again.
    ' This function raises an error (times out to prevent infinite loop) after N seconds.
    Const MAXIMUM_WAIT_IN_SECONDS As Long = 10
    Const INTERVAL_WAIT_IN_SECONDS As Long = 1

    Dim timeToStopAt As Date
    timeToStopAt = DateAdd("s", MAXIMUM_WAIT_IN_SECONDS, Now)

    Do While Now < timeToStopAt
        Dim outputWorkbook As Workbook
        Set outputWorkbook = GetFileOrNothing()

        If Not (outputWorkbook Is Nothing) Then Exit Do
        Application.Wait DateAdd("s", INTERVAL_WAIT_IN_SECONDS, Now)
        DoEvents
    Loop

    If outputWorkbook Is Nothing Then
        Err.Raise vbObjectError + 5, , "Failed to access file within the specified time frame."
    End If

    Set GetFileOrWait = outputWorkbook
End Function