简体   繁体   中英

Adding binary file to archive

I need to add existing binary file to an archive. I found an example but it is only good for text files. How can I do it with binary, say pdf? Here is the code for text file.

using (FileStream zipToOpen = new FileStream(@"c:\users\exampleuse\release.zip", FileMode.Open))
        {
            using (ZipArchive archive = new ZipArchive(zipToOpen, ZipArchiveMode.Update))
            {
                ZipArchiveEntry readmeEntry = archive.CreateEntry("Readme.txt");
                using (StreamWriter writer = new StreamWriter(readmeEntry.Open()))
                {
                        writer.WriteLine("Information about this package.");
                        writer.WriteLine("========================");
                }
            }
        }

You can just open the file and write directly to the stream of zip entry:

ZipArchiveEntry readmeEntry = archive.CreateEntry("asd.pdf");
using (var stream = readmeEntry.Open())
using (var file = File.OpenRead(@"C:\somewhere\asd.pdf"))
{
    file.CopyTo(stream);
}

This works for any file type, just make sure the extension matches.

You just need to use BinaryWriter to add binary data. Below is example for byte[]. In order to get that data you can read existent file, get output of PDF generation library etc. Overall you can just take any stream.

using (ZipArchive archive = new ZipArchive(zipToOpen, ZipArchiveMode.Update))
{
    ZipArchiveEntry readmeEntry = archive.CreateEntry("test.dat");
    byte[] someData = {10, 20, 30};
    using (BinaryWriter writer = new BinaryWriter(readmeEntry.Open()))
    {
        writer.Write(someData);
    }
}

The sample shows how to create a StreamWriter and write data to the archive entry. Since the StreamWriter is intended for text, you would need to access the Stream or use a different writer for binary. Below is a quick sample of how to read the desired binary file and write the bytes to the stream in a similar approach.

    string fileToZipPath = @"c:\users\exampleuse\binaryfile.exe"; 

    using (FileStream zipToOpen = new FileStream(@"c:\users\exampleuse\release.zip", FileMode.Open))
    {
        using (ZipArchive archive = new ZipArchive(zipToOpen, ZipArchiveMode.Update))
        {
            ZipArchiveEntry readmeEntry = archive.CreateEntry("BinaryFile.exe");
            using (Stream writer = readmeEntry.Open())
            {
                using (FileStream fileToCompress = new FileStream (fileToZipPath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
                {
                    fileToCompress.CopyTo(writer);
                }
            }
        }
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM