Jun 16 2022 05:43 AM
Jun 16 2022 05:43 AM
I should add a list of files into a ZIP. Procedure code is like this
Sub CreateZip Dim FileList As New ArrayList 'List of File Paths to be added to the ZIP For Each path in FileList Try AddFileToZip(ZipFilePath, path.ToString) Catch (ex as New Exception) .... End Try Next End Sub
And this is AddFileToZip
Public Sub AddFileToZip(ByVal zipFilename As String, ByVal fileToAdd As String) Using zip As Package = System.IO.Packaging.Package.Open(zipFilename, FileMode.OpenOrCreate) Dim destFilename As String = ".\" & Path.GetFileName(fileToAdd) Dim uri As Uri = PackUriHelper.CreatePartUri(New Uri(destFilename, UriKind.Relative)) If zip.PartExists(uri) Then zip.DeletePart(uri) End If Dim part As PackagePart = zip.CreatePart(uri, "", CompressionOption.Normal) Using fileStream As New FileStream(fileToAdd, FileMode.Open, FileAccess.Read) Using dest As Stream = part.GetStream() CopyStream(fileStream, dest) End Using End Using End Using End Sub
At runtime, I get this error message
The process cannot access the file [ZipFilePath] because it is being used by another process
this error is raised randomly, maybe on adding small files into the Zip. If I place breakpoints and run procedure in debug mode, it works.
It seems clear that procedure thread is not synchronized with IO, so that my procedure loop continues even if IO is still adding processed file into Zip (ie VB.NET is faster than IO).
I also tried to place a Thread.Sleep(1000) before AddFileToZip, but this may be not enough to synchronize the two processes. Placing Thread.Sleep(2000) seems to make procedure work, but it may slow down dramaticly performances (I should pack more than 50 files into my Zip).
So, how can I force my loop to "wait" until IO Process has released ZIP file?
Jun 16 2022 07:38 PM
Thanks for posting your issue here.
However this platform is used for how-to discussions and sharing best practices for building any app with .NET.Since your issue is a technical question, welcome to post it in Microsoft Q&A forum, the support team and communities on Microsoft Q&A will help you for any technical questions.
Besides, it will be appreciated if you can share it here once you post this technical question Microsoft Q&A.
Jun 17 2022 03:01 AM
Jun 17 2022 03:20 AM
Nov 18 2022 02:28 AM
@mr_anto Sorry if this is late, probably you already fixed it.
Using zip As Package = System.IO.Packaging.Package.Open(zipFilename, FileMode.OpenOrCreate)
this is because every time you add a file, you try to reopen the zip, which is not very useful.
Open it once, and then add all files to it.