C#ZipArchive:未创建zip文件

时间:2018-03-14 02:35:09

标签: c# ziparchive

我尝试使用以下代码首先将bytes转换为compressed bytes并尝试创建zip文件,但不会生成文件。请有人建议!

byte[] result;
var X = 86251;
byte[] compressedBytes;

using (FileStream SourceStream = File.Open(filename, FileMode.Open))
{
    SourceStream.Seek(0, SeekOrigin.Begin);

    result = new byte[X];

    await SourceStream.ReadAsync(result, 0, X);
}

string fileName = "Export_" + DateTime.Now.ToString("yyyyMMddhhmmss") + ".zip";
using (var outStream = new MemoryStream())
{
    using (var archive = new ZipArchive(outStream, ZipArchiveMode.Create, true))
    {
        var fileInArchive = archive.CreateEntry(fileName, CompressionLevel.Optimal);
        using (var entryStream = fileInArchive.Open())
        using (var fileToCompressStream = new MemoryStream(result))
        {
            fileToCompressStream.CopyTo(entryStream);
        }
    }
    compressedBytes = outStream.ToArray();
}

1 个答案:

答案 0 :(得分:2)

您无法在任何地方创建实际文件。你只是写一个内存流。将其更改为写入文件。

using (var outStream = new File.Create(fileName))
{
    using (var archive = new ZipArchive(outStream, ZipArchiveMode.Create, true))
    {
        var fileInArchive = archive.CreateEntry(filename, CompressionLevel.Optimal);
        using (var entryStream = fileInArchive.Open())
        using (var fileToCompressStream = new MemoryStream(result))
        {
            fileToCompressStream.CopyTo(entryStream);
        }
    }
}