Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

using 7zip sdk to compress a file, but can not decompress using winrar or 7zip

I downloaded the SDK 7zip from here.

Then I used this code to compress a file to 7zip:

private static void CompressFileLZMA(string inFile, string outFile)
{
    Encoder coder = new SevenZip.Compression.LZMA.Encoder();

    using (FileStream input = new FileStream(inFile, FileMode.Open))
    using (FileStream output = new FileStream(outFile, FileMode.Create))
    {
        coder.Code(input, output, -1, -1, null);
        output.Flush();
    }
}

I tried both the SDK versions 9.20 and 9.22 beta on the site.

The compression seems working to compress my file from: 1.6 MB to 239 KB.

However, if I use WinRar or 7zip to decompress. the archive file is not recognized by them, the error is like

"unknown archive file or damaged file"

Any idea for this?

like image 348
olidev Avatar asked Dec 27 '22 10:12

olidev


1 Answers

have you looked at the example project included with the SDK? It is in the CS\7zip\Compress\LzmaAlone\ folder and it contains a file LmzaAlone.cs which has some stuff which encodes a file. It does things like this before it writes out the compressed data:

CoderPropID[] propIDs = 
{
    CoderPropID.DictionarySize,
    CoderPropID.PosStateBits,
    CoderPropID.LitContextBits,
    CoderPropID.LitPosBits,
    CoderPropID.Algorithm,
    CoderPropID.NumFastBytes,
    CoderPropID.MatchFinder,
    CoderPropID.EndMarker
};
object[] properties = 
{
    (Int32)(dictionary),
    (Int32)(posStateBits),
    (Int32)(litContextBits),
    (Int32)(litPosBits),
    (Int32)(algorithm),
    (Int32)(numFastBytes),
    mf,
    eos
};

Compression.LZMA.Encoder encoder = new Compression.LZMA.Encoder();
encoder.SetCoderProperties(propIDs, properties);
encoder.WriteCoderProperties(outStream);
if (trainStream != null)
{
    CDoubleStream doubleStream = new CDoubleStream();
    doubleStream.s1 = trainStream;
    doubleStream.s2 = inStream;
    doubleStream.fileIndex = 0;
    inStream = doubleStream;
    long trainFileSize = trainStream.Length;
    doubleStream.skipSize = 0;
    if (trainFileSize > dictionary)
        doubleStream.skipSize = trainFileSize - dictionary;
    trainStream.Seek(doubleStream.skipSize, SeekOrigin.Begin);
    encoder.SetTrainSize((uint)(trainFileSize - doubleStream.skipSize));
}
// only now does it write out the compressed data:
encoder.Code(inStream, outStream, -1, -1, null);

so it looks like you need to write out a few file headers first to give the details about the compression data that is coming.

if you download the source for 7Zip then you will find that in the doc folder there is a file 7zFormat.txt which contains a description of the format of the 7 zip files. This might help you create valid archives.

like image 107
Sam Holder Avatar answered Jan 29 '23 14:01

Sam Holder