Moving file directly into zip file

I'm trying move Source_File.mp4 into Destination_Zip.zip directly. I'm currently trying it by creating a new entry Transfer.mp4 and copying the bytes over. The code runs to the end but the file is never added to the ZIP file. I'm not sure if I'm missing something or if this isn't possible.

string sourceFile = basePath + "Source_File.mp4";
string destinationZip = basePath + "Desintation_Zip.zip";

using (var file = File.OpenRead(destinationZip))
{
    MemoryStream memoryStream = new MemoryStream();
    memoryStream.SetLength(file.Length);
    file.Read(memoryStream.GetBuffer(), 0, (int)file.Length);

    using (var zip = new ZipArchive(memoryStream, ZipArchiveMode.Update))
    {
        var entry = zip.CreateEntry("Transfer.mp4");
        using (var destinationStream = entry.Open())
        using (var sourceStream = File.OpenRead(sourceFile))
        {
            sourceStream.CopyTo(destinationStream);
        }
    }
}

Upvotes: 0

Views: 210

Answers (2)

pneuma
pneuma

Reputation: 977

My guess is that even though you've read the file and altered it, you didn't write anything back, i.e. changes persisted to MemoryStream, and didn't go anywhere after that.

You could try this (assumes you're using System.IO.Compression.ZipFile):

using (var zip = ZipFile.Open(destinationZip, ZipArchiveMode.Update))
{
    var entry = zip.CreateEntry("Transfer.mp4");
    using (var destinationStream = entry.Open())
    using (var sourceStream = File.OpenRead(sourceFile))
    {
        sourceStream.CopyTo(destinationStream);
    }
}

Or, if you're using ICSharpCode.SharpZipLib.Zip.ZipFile, do this:

using (var fileStream = new FileStream(destinationZip, FileMode.Open))
using (var zip = new ZipArchive(fileStream, ZipArchiveMode.Update))
{
    var entry = zip.CreateEntry("Transfer.mp4");
    using (var destinationStream = entry.Open())
    using (var sourceStream = File.OpenRead(sourceFile))
    {
        sourceStream.CopyTo(destinationStream);
    }
}

Upvotes: 2

I'm still not sure why my initial code did not work, but I got it working by doing this instead:

string sourceFile = basePath + "Source_File.mp4";
string destinationZip = basePath + "Desintation_Zip.zip";

using (var destinationZipFileStream = new FileStream(destinationZip, FileMode.Open))
using (var destinationZipArchive = new ZipArchive(destinationZipFileStream, ZipArchiveMode.Update))
{
    ZipArchiveEntry destinationWriter = destinationZipArchive.CreateEntry("Transfer.mp4");
    using (var writer = new StreamWriter(destinationWriter.Open()))
    using (var sourceStream = File.OpenRead(sourceFile))
    {
        sourceStream.CopyTo(writer.BaseStream);
    }
}   

Note: you will need to double check to make sure the file doesn't exist already or else you'll make duplicate files this way.

Upvotes: 0

Related Questions