加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

c# – 直接从对象创建zip文件而不使用磁盘IO

发布时间:2020-12-15 23:44:55 所属栏目:百科 来源:网络整理
导读:我正在编写一个REST API,它将接收一个 JSON请求对象.请求对象必须序列化为JSON格式的文件;该文件必须压缩成一个zip文件,ZIP文件必须发布到另一个服务,我将不得不反序列化ZIP文件.这一切都是因为我要调用的服务要求我将数据发布为ZIP文件.我试图看看我是否可
我正在编写一个REST API,它将接收一个 JSON请求对象.请求对象必须序列化为JSON格式的文件;该文件必须压缩成一个zip文件,ZIP文件必须发布到另一个服务,我将不得不反序列化ZIP文件.这一切都是因为我要调用的服务要求我将数据发布为ZIP文件.我试图看看我是否可以避免磁盘IO.有没有办法直接将对象转换为表示内存中ZIP内容的字节数组而不是上述所有步骤?

注意:我更喜欢使用.net框架库来实现这一点(与外部库相比)

解决方法

是的,可以在内存上完全创建一个zip文件,下面是一个使用SharpZip库的示例(更新:最后添加了ZipArchive的示例):

public static void Main()
{
    var fileContent = Encoding.UTF8.GetBytes(
        @"{
            ""fruit"":""apple"",""taste"":""yummy""
          }"
        );


    var zipStream = new MemoryStream();
    var zip = new ZipOutputStream(zipStream);

    AddEntry("file0.json",fileContent,zip); //first file
    AddEntry("file1.json",zip); //second file (with same content)

    zip.Close();

    //only for testing to see if the zip file is valid!
    File.WriteAllBytes("test.zip",zipStream.ToArray());
}

private static void AddEntry(string fileName,byte[] fileContent,ZipOutputStream zip)
{
    var zipEntry = new ZipEntry(fileName) {DateTime = DateTime.Now,Size = fileContent.Length};
    zip.PutNextEntry(zipEntry);
    zip.Write(fileContent,fileContent.Length);
    zip.CloseEntry();
}

您可以使用Nuget命令PM>获得SharpZip.安装包SharpZipLib

更新:

Note : I’d prefer accomplishing this using .net framework libraries (as against external libraries)

以下是使用System.IO.Compression.Dll中的内置ZipArchive的示例

public static void Main()
{
    var fileContent = Encoding.UTF8.GetBytes(
        @"{
            ""fruit"":""apple"",""taste"":""yummy""
          }"
        );

    var zipContent = new MemoryStream();
    var archive = new ZipArchive(zipContent,ZipArchiveMode.Create);

    AddEntry("file1.json",archive);
    AddEntry("file2.json",archive); //second file (same content)

    archive.Dispose();

    File.WriteAllBytes("testa.zip",zipContent.ToArray());
}


private static void AddEntry(string fileName,ZipArchive archive)
{
    var entry = archive.CreateEntry(fileName);
    using (var stream = entry.Open())
        stream.Write(fileContent,fileContent.Length);

}

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读