C# - 压缩字节[]

时间:2016-04-06 14:07:00

标签: c# .net

我收到一个zip文件base64字符串,转换为byte [],在内存中打开,修改内容,然后'压缩'新的byte []再次为base64字符串。

我的问题,我不知道如何压缩'新的byte []到zip格式。

public string ModifyZipContent(string base64) {
    ZipPackage zipPackage = null;
    MemoryStream memoryStream = null;

    long lenght;

    byte[] data = Convert.FromBase64String(base64);
    byte[] buffer;
    byte[] newData;

    int arrayOffset = 0;

    memoryStream = new MemoryStream();
    memoryStream.Write(data, 0, data.Length);

    zipPackage = (ZipPackage)Package.Open(memoryStream, FileMode.Open);

    PackagePartCollection zipParts = zipPackage.GetParts();

    // this is awful
        foreach(ZipPackagePart zipPart in zipParts) {
            using(Stream stream = zipPart.GetStream()) {
                arrayOffset += (int)stream.Length;
            }
        }

        newData = new byte[arrayOffset];
    // end

    arrayOffset = 0;
    foreach(ZipPackagePart zipPart in zipParts) {
        using(Stream stream = zipPart.GetStream()) {
            lenght = stream.Length;
            buffer = new byte[lenght];

            stream.Read(buffer, 0, (int)lenght);

            Buffer.BlockCopy(buffer, 0, newData, arrayOffset, buffer.Length);
            arrayOffset += buffer.Length;
        }
    }

    return Convert.ToBase64String(newData);
}

1 个答案:

答案 0 :(得分:0)

我还没有对此进行过全面测试,但这些方面的内容应该有效......

isset($_POST['somefield']