从C#中的多个内存文件创建Zip存档 [英] Create Zip archive from multiple in memory files in C#

查看:487
本文介绍了从C#中的多个内存文件创建Zip存档的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当文件当前在内存中时,是否有一种方法来创建包含多个文件的Zip存档?我想保存的文件实际上只是文本,并存储在我的应用程序中的字符串类。但我想将多个文件保存在一个单独的自包含存档。

Is there a way to create a Zip archive that contains multiple files, when the files are currently in memory? The files I want to save are really just text only and are stored in a string class in my application. But I would like to save multiple files in a single self-contained archive. They can all be in the root of the archive.

使用SharpZipLib可以做到这一点很不错。

It would be nice to be able to do this using SharpZipLib.

推荐答案

为此使用 ZipEntry PutNextEntry()下面显示了如何做一个文件,但对于一个内存对象只使用一个MemoryStream

Use ZipEntry and PutNextEntry() for this. The following shows how to do it for a file, but for an in-memory object just use a MemoryStream

FileStream fZip = File.Create(compressedOutputFile);
ZipOutputStream zipOStream = new ZipOutputStream(fZip);
foreach (FileInfo fi in allfiles)
{
    ZipEntry entry = new ZipEntry((fi.Name));
    zipOStream.PutNextEntry(entry);
    FileStream fs = File.OpenRead(fi.FullName);
    try
    {
        byte[] transferBuffer[1024];
        do
        {
            bytesRead = fs.Read(transferBuffer, 0, transferBuffer.Length);
            zipOStream.Write(transferBuffer, 0, bytesRead);
        }
        while (bytesRead > 0);
    }
    finally
    {
        fs.Close();
    }
}
zipOStream.Finish();
zipOStream.Close();

这篇关于从C#中的多个内存文件创建Zip存档的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆