添加二进制文件到存档

时间:2018-05-10 19:58:21

标签: c# zipfile

我需要将现有的二进制文件添加到存档中。我找到了一个例子,但它只适用于文本文件。我怎么能用二进制文件来说,比如pdf? 这是文本文件的代码。

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("========================");
                }
            }
        }

1 个答案:

答案 0 :(得分:0)

该示例显示如何创建StreamWriter并将数据写入归档条目。由于StreamWriter用于文本,因此您需要访问Stream或使用不同的二进制编写器。下面是如何读取所需二进制文件并以类似方法将字节写入流中的快速示例。

    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);
                }
            }
        }
    }