Good morning,
I have a process which successfully generates a number of PDFs in a folder, and then compresses that folder into an unencrypted zip file.
I have used the code from a previous question:
https://www.telerik.com/forums/zip-content-of-a-folder-into-an-encrypted-zip-file
So my code is as follows:
public static void CreateZipFileFromDirectory(string sourceDirectoryName, string destinationArchiveFileName)
{
char[] directorySeparatorChar = new char[] { Path.DirectorySeparatorChar, Path.AltDirectorySeparatorChar };
ZipArchiveMode archiveMode = System.IO.File.Exists(destinationArchiveFileName) ? ZipArchiveMode.Update : ZipArchiveMode.Create;
if (!string.IsNullOrEmpty(sourceDirectoryName))
{
using FileStream archiveStream = System.IO.File.Open(destinationArchiveFileName, FileMode.OpenOrCreate);
using ZipArchive archive = new ZipArchive(archiveStream, archiveMode, leaveOpen: false, entryNameEncoding: null);
foreach (string fileName in Directory.GetFiles(sourceDirectoryName))
{
using FileStream file = System.IO.File.OpenRead(fileName);
int length = fileName.Length - sourceDirectoryName.Length;
string entryName = fileName.Substring(sourceDirectoryName.Length, length);
entryName = entryName.TrimStart(directorySeparatorChar);
using ZipArchiveEntry entry = archive.CreateEntry(entryName);
using Stream entryStream = entry.Open();
file.CopyTo(entryStream);
}
}
}
This creates the zip file and adds the first PDF successfully, but gives an error when trying to add the second PDF
"The process cannot access the file 'filename.zip' because it is being used by another process."
I have tried setting the leaveOpen parameter for the ZipArchive to true and to false but that gives me the same error.
Any ideas what I've missed?
Richard