Please note, that the stream given to the AddFile
method is not closed after the method is finished. It is responsibility of the caller to close the given stream if needed.
Also please note, that the "File in Access" error doesn't depend on the FileAccess.ReadWrite
, but on the FileShare
which is by default FileShare.None
.
What you probably need is to use the AddFile(string, string)
method. It opens the file with following settings (and also closes it when reading is finished):
File.Open(path, FileMode.Open, FileAccess.Read, FileShare.Read);
So I suggest you to update your code like this:
using (MemoryStream memoryStream = new MemoryStream(capacity))
{
// zipCommandswill have the path for files
foreach (Medispan.Zip.ZipCommand zipCommand in zipCommands)
{
if (zipCommand.IsDirectory)
continue;
using (ZipArchive archive = new ZipArchive(memoryStream, ArchiveStreamCloseMode.LeaveOpen))
{
string zipArchiveFilePath = zipCommand.Destination.ToString();
try
{
archive.AddFile(zipCommand.Source.ToString(), zipArchiveFilePath);
}
catch (ZipException ex)
{
_traceSource.TraceEvent(TraceEventType.Verbose, 1, "ZipException " + ex);
if (ex.ProblemType != ArchiveProblemType.FileExists)
throw;
}
catch (Exception ex)
{
_traceSource.TraceEvent(TraceEventType.Verbose, 1, "Exception " + ex);
throw;
}
}
}
memoryStream.Seek(0, SeekOrigin.Begin);
}