简体   繁体   English

使用 ZipArchive C# 将压缩的 Byte[] 下载到磁盘

[英]Download compressed Byte[] to disk using ZipArchive C#

I have a compressed byte array that I would like to download to the server as a.zip file.我有一个压缩字节数组,我想以 .zip 文件的形式下载到服务器。 Using the following code, the file size shows the correct compressed size.使用以下代码,文件大小显示正确的压缩大小。 But when I go to open the file it says the.zip file is invalid.但是当我 go 打开文件时,它说 .zip 文件无效。 Do I need to somehow set the content type to application/zip?我是否需要以某种方式将内容类型设置为 application/zip?

using var compressedStream = new MemoryStream(fileBytes);
var fileStream = new FileStream(@"<file directory\xxx.zip", FileMode.Create, FileAccess.Write);
            compressedStream.CopyTo(fileStream);
            fileStream.Dispose();

File was zipped using the following snippet:使用以下代码段压缩文件:

 byte[]? archiveFile = Array.Empty<byte>();
                        byte[]? fileBytes = System.IO.File.ReadAllBytes(file);

                        using var archiveStream = new MemoryStream();

                        using (var archive = new ZipArchive(archiveStream, ZipArchiveMode.Create, true))
                        {
                            var zipArchiveEntry = archive.CreateEntry(file, CompressionLevel.SmallestSize);
                            using var zipStream = zipArchiveEntry.Open();
                            zipStream.Write(fileBytes, 0, fileBytes.Length);
                        }

                        archiveFile = archiveStream.ToArray();

Lately I'm busy building a service which retrieves files from an API as a byte[] with a list of properties, one of them containing the file extension.最近我正忙于构建一个服务,该服务从 API 检索文件作为具有属性列表的字节 [],其中一个包含文件扩展名。 The service stores these files in a Blob Storage with the right file extension.该服务将这些文件存储在具有正确文件扩展名的 Blob 存储中。 To create a file from a byte[] you can use the following code.要从 byte[] 创建文件,您可以使用以下代码。

File.WriteAllBytes("somePath/file.zip", theByteArray); File.WriteAllBytes("somePath/file.zip", theByteArray);

File can be found in the given path.文件可以在给定的路径中找到。 If you don't specify a specific path the file will be found in the somewhere inside the 'bin' folder of your project after a completed run.如果您未指定特定路径,则在完成运行后,该文件将在项目的“bin”文件夹内的某处找到。 Remember to add the.zip extension in your first argument or else a file will be created with no extension.请记住在您的第一个参数中添加 .zip 扩展名,否则将创建一个没有扩展名的文件。 Pass in as a second argument a byte[] .作为第二个参数传入一个byte[] Works fine here.在这里工作正常。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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