开发者

sharpziplib compressed files to be uncompressed externally

开发者 https://www.devze.com 2023-03-10 14:43 出处:网络
I have a scenario where by I want to zip an email attachment using SharpZipLib. Then the end user will open the attachment and will unzip the attached file.

I have a scenario where by I want to zip an email attachment using SharpZipLib. Then the end user will open the attachment and will unzip the attached file.

Will t开发者_StackOverflow社区he file originally zipped file using SharpZipLib be easily unzipped by other programs for my end user?


It depends on how you use SharpZipLib. There is more than one way to compress the data with this library.

Here is example of method that will create a zip file that you will be able to open in pretty much any zip aware application:

private static byte[] CreateZip(byte[] fileBytes, string fileName)
{
    using (var memoryStream = new MemoryStream())
    using (var zipStream = new ZipOutputStream(memoryStream))
    {
        var crc = new Crc32();
        crc.Reset();
        crc.Update(fileBytes);

        var zipEntry =
            new ZipEntry(fileName)
            {
                Crc = crc.Value,
                DateTime = DateTime.Now,
                Size = fileBytes.Length
            };
        zipStream.PutNextEntry(zipEntry);
        zipStream.Write(fileBytes, 0, fileBytes.Length);
        zipStream.Finish();
        zipStream.Close();
        return memoryStream.ToArray();
    }
}

Usage:

var fileBytes = File.ReadAllBytes(@"C:/1.xml");

var zipBytes = CreateZip(fileBytes, "MyFile.xml");

File.WriteAllBytes(@"C:/2.zip", zipBytes);

This CreateZip method is optimized for the cases when you already have bytes in memory and you just want to compress them and send without even saving to disk.

0

精彩评论

暂无评论...
验证码 换一张
取 消