Walter Fabio Simoni
Walter Fabio Simoni

Reputation: 5729

Compressing a file from memory with SevenZipSharp, stranges mistakes

I download the SevenZipSharp Lib in order to compress some files.

I used this in order to compress a file :

var libPath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ProgramFiles), "7-zip", "7z.dll");
SevenZip.SevenZipCompressor.SetLibraryPath(libPath);
SevenZip.SevenZipCompressor compressor = new SevenZipCompressor();
compressor.CompressFiles(@"C:\myTestFile.mdf", new string[] { @"C:\myTestFileCompressed.7z" });

With this, my file is compressed whitout problem. I can decompressed it.

Now...i would like to compress the same file, but, instead of compress directly the file, i would like to :

Here is my try :

string strToCompress = File.ReadAllText(@"C:\myTestFile.mdf");
SevenZipCompressor compressor = new SevenZipCompressor();
byte[] byteArrayToCompress = Encoding.ASCII.GetBytes(text);
MemoryStream stream = new MemoryStream(byteArrayToCompress);
MemoryStream streamOut = new MemoryStream();
compressor.CompressStream(stream, streamOut);
string strcompressed = Encoding.ASCII.GetString(streamOut.ToArray());
File.WriteAllText(@"C:\myfileCompressed.7z",strcompressed);

My problem is very simple :

If i compare the size produced by these 2 methods, it's 3 603 443 bytes vs 3 604 081 bytes. In addition, i cannot uncompressed the file produced by the second method.

Maybe it's because i used ASCII encoding, but my file to compress is not a Text, it's a binary file.

Anyone could explain me how solving it please ? I need to read my file to a string and compress it. ( i don't want to read the file directly to a byte[]).

Thanks a lot,

Best regards,

Nixeus

Upvotes: 1

Views: 1457

Answers (1)

Hans Passant
Hans Passant

Reputation: 941465

You cannot put binary data into a string, not every byte value has a Unicode codepoint. Using ASCII encoding will similarly always cause irretrievable data loss, it only has characters for byte values 0 through 127, higher values will produce a ?

You certainly can convert a byte[] to a string, it needs to be encoded. The standard encoding that's used for that is available in .NET from the Convert.ToBase64String() method. You recover the byte[] again with Convert.FromBase64String(). Inevitably it won't be as compact, it will be 4/3 bigger as the original data in a byte[].

You can never produce a valid .7z archive that way, it of course uses the most compact possible storage and that is bytes. You must pass a FileStream to the CompressStream() method.

Upvotes: 1

Related Questions