AbbasFaisal
AbbasFaisal

Reputation: 1490

The stream is invalid or no corresponding signature was found

I am trying to use SevenZipSharp to compress and decompress a memory stream. Compression is working fine but decompression is not. I think SevenZipSharp is not able to figure the archive type from the stream.

SevenZipCompressor compress = new SevenZip.SevenZipCompressor();
compress.CompressionLevel = CompressionLevel.Normal;
compress.CompressionMethod = CompressionMethod.Lzma

using (MemoryStream memStream = new MemoryStream())
{
    compress.CompressFiles(memStream, @"d:\Temp1\MyFile.bmp");

    using (FileStream file = new FileStream(@"d:\arch.7z", FileMode.Create, System.IO.FileAccess.Write))
    {
        memStream.CopyTo(file);
    }
}

//works till here, file is created
Console.Read();

using (FileStream file = new FileStream(@"d:\arch.7z", FileMode.Open, System.IO.FileAccess.Read))
{
    using (MemoryStream memStream = new MemoryStream())
    {
        file.CopyTo(memStream);

        //throws exception here on this line
        using (var extractor = new SevenZipExtractor(memStream))
        {
            extractor.ExtractFiles(@"d:\x", 0);
        }
    }
}

Upvotes: 2

Views: 662

Answers (1)

RMH
RMH

Reputation: 837

Try to see if your output file can be loaded using the 7Zip client. I'm guessing that it will fail.

The problem lies in the writing to the memorystream. Say, you write 100 bytes to the stream, it will be on position 100. When you use CopyTo, the stream will be copied from the current position, not the start of the stream.

So you'll have to reset the position to 0 after reading/writing to allow the next reader to read all the data. For instance when creating the 7Zip file:

using (MemoryStream memStream = new MemoryStream())
{
    // Position starts at 0
    compress.CompressFiles(memStream, @"d:\Temp1\MyFile.bmp");
    // Position is now N

    memStream.Position = 0; // <-- Reset the position to 0.

    using (FileStream file = new FileStream(@"d:\arch.7z", FileMode.Create, System.IO.FileAccess.Write))
    {
        // Will copy all data in the stream from current position till the end of the stream.
        memStream.CopyTo(file);
    }
}

Upvotes: 3

Related Questions