使用 CopyHere 写入文件而不使用 WScript.Sleep [英] Write to file using CopyHere without using WScript.Sleep

查看:39
本文介绍了使用 CopyHere 写入文件而不使用 WScript.Sleep的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我编写了一个小的 VBScript 来创建一个 .zip 文件,然后将指定文件夹的内容复制到该 .zip 文件中.

I've written a small VBScript to creates a .zip file and then copies the contents of a specified folder into that .zip file.

我一个一个地复制文件是有原因的(我知道我可以一次完成很多工作).但是我的问题是当我尝试在每次循环迭代之间没有 WScript.Sleep 的情况下逐个复制它们时,我得到找不到文件或没有读取权限".错误;如果我在每次写入后放置一个 WScript.Sleep 200 它可以工作但不是 100% 的时间.

I copy the files over one by one for a reason (I know I can do the whole lot at once). However my problem is when I try to copy them one by one without a WScript.Sleep between each loop iteration I get a "File not found or no read permission." error; if I place a WScript.Sleep 200 after each write it works but not 100% of the time.

我很想摆脱睡眠功能而不是依赖它,因为根据文件大小,写入可能需要更长的时间,因此 200 毫秒可能不够等.

Pretty much I'd like to get rid of the Sleep function and not rely on that because depending on the file size it may take longer to write therefore 200 milliseconds may not be enough etc.

正如您在下面的一小段代码中看到的那样,我遍历文件,然后如果它们与扩展名匹配,则将它们放入 .zip (zipFile)

As you can see with the small piece of code below, I loop through the files, then if they match the extension I place them into the .zip (zipFile)

For Each file In folderToZip.Items
    For Each extension In fileExtensions
        if (InStr(file, extension)) Then
            zipFile.CopyHere(file)
            WScript.Sleep 200
            Exit For
        End If
    Next
Next

关于如何停止依赖睡眠功能的任何建议?

Any suggestions on how I can stop relying on the Sleep function?

谢谢

推荐答案

这就是我们在 VB6 中的做法.在 zip 上调用 CopyHere 后,我们等待异步压缩像这样完成

This is how we do it in VB6. After calling CopyHere on the zip we wait for async compression to complete like this

    Call Sleep(100)
    Do
        Do While Not pvCanOpenExclusive(sZipFile)
            Call Sleep(100)
        Loop
        Call Sleep(100)
    Loop While Not pvCanOpenExclusive(sZipFile)

辅助函数看起来像这样

Private Function pvCanOpenExclusive(sFile As String) As Boolean
    Dim nFile       As Integer

    nFile = FreeFile
    On Error GoTo QH
    Open sFile For Binary Access Read Lock Write As nFile
    Close nFile
    pvCanOpenExclusive = True
QH:
End Function

好的副作用是,即使压缩失败,也不会陷入无限循环.

Nice side-effect is that even if zipping fails this will not end up in infinite loop.

访问由 zipfldr.dll 关闭的 zip 文件时会出现问题,即 pvCanOpenExclusive 返回 true 时.

The trouble comes when accessing the zip-file when it's closed by zipfldr.dll, that is when pvCanOpenExclusive returns true.

这篇关于使用 CopyHere 写入文件而不使用 WScript.Sleep的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆