nemostyle
nemostyle

Reputation: 814

How to zip file in code in c#?

I am trying to zip file in code. The error is in static void method CopyStream at line "dest.Write(buffer, 0, len);". Error is "Bad state (unknown compression method(0x4D))". Any idea why is this happening?

    public byte[] ZippingFile()
    {
        MemoryStream dest = new MemoryStream();
        FileStream file = new FileStream(tbPath.Text + @"\" +    tbFileName.Text, FileMode.Open, FileAccess.Read);
        byte[] array = new byte[0];
        try
        {
            ZlibDecompression(file, dest);
            array = dest.ToArray();

        }
        catch (Exception ex)
        {
            MessageBox.Show("Error: " + ex.Message, "Error", MessageBoxButtons.OK,
                            MessageBoxIcon.Error);
        }
        finally
        {
            file.Close();
            dest.Close();
        }
        return niz;
    }


    private void ZlibDecompression(Stream src, MemoryStream dest)
    {
        src.Seek(0, SeekOrigin.Begin);
        using (ZlibStream zlibStreamOut = new ZlibStream(dest, CompressionMode.Decompress, CompressionLevel.Level4, true))
        {
            CopyStream(src, zlibStreamOut);
            zlibStreamOut.Close();
            dest.Seek(0, SeekOrigin.Begin);
        }
    }

    static void CopyStream(Stream src, Stream dest)
    {
        byte[] buffer = new byte[1024];
        int len = src.Read(buffer, 0, buffer.Length);
        while (len > 0)
        {
            dest.Write(buffer, 0, len);
            len = src.Read(buffer, 0, buffer.Length);
        }
        dest.Flush();
    }

Upvotes: 0

Views: 132

Answers (1)

PaulF
PaulF

Reputation: 6773

If you are trying to "zip" the file - then you should be using CompressionMode.Compress. The "unknown compression method(0x4D)" probably means there is a letter M in the position the decompression routine expects to find a code for how the file was compressed - maybe the very first character in your file.

Upvotes: 1

Related Questions