Want to protect your cyber security and still get fast solutions? Ask a secure question today.Go Premium

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 2581
  • Last Modified:

BZip2 a Stream with SharpZipLib

I am having trouble with implementing SharpZipLib for my specific need.
So, I need an example that is on point.

I want to open a file with openFileDialog and BZip2 it in memory and then
print out the ToBase64String of the zipped stream.

All of the in/out streams and byte array conversions are getting me tied in knots.
--brian
0
Brian Bush
Asked:
Brian Bush
  • 3
  • 3
1 Solution
 
Brian BushSolutions ArchitectAuthor Commented:
I should also mention I am using the SharpZipLib as it states in the title.

I will also need to be able to reverse it, but I plan to open another
question for that one, so if you solve both, you can double up on the points.
--brian
0
 
AGBrownCommented:
Here's a short snippet of code:

using System;
using System.Data;
using System.Data.SqlClient;
using System.IO;
using System.Text;
using ICSharpCode.SharpZipLib.BZip2;

namespace ConsoleApplication1
{

      class Program
      {
            const string FILE_PATH = @"C:\test.txt";
            static void Main(string[] args)
            {
                  CheckFileExists();

                  byte[] originalBytes = null;
                  byte[] compressedBytes = null;

                  //       open the file into a stream
                  using (FileStream fs = File.OpenRead(FILE_PATH))
                  {
                        //      and read into a byte array
                        originalBytes = new byte[fs.Length];
                        fs.Read(originalBytes, 0, (int)fs.Length);
                  }

                  //      compress onto a memory stream
                  using (MemoryStream mem = new MemoryStream())
                  {
                        //      now create the compression stream based on the memory stream
                        using (BZip2OutputStream comp = new BZip2OutputStream(mem))
                        {
                              comp.Write(originalBytes, 0, originalBytes.Length);
                        }      // the using statement ensures a flush, finalize and close

                        //      now we write the memorystream to the interim byte array to show there are now hidden tricks
                        compressedBytes = mem.ToArray();
                  }

                  //      COnvert the bytes to a string
                  string strInterimStorage = Convert.ToBase64String(compressedBytes);

                  Console.WriteLine("Original string (base64)");
                  Console.WriteLine(Convert.ToBase64String(originalBytes));
                  Console.WriteLine("Compressed string (base64)");
                  Console.WriteLine(strInterimStorage);

                  byte[] receivedCompressedBase64 = Convert.FromBase64String(strInterimStorage);
                  byte[] decompressedBytes;
                  //      decompress using a memory stream
                  using (MemoryStream rec = new MemoryStream(receivedCompressedBase64))
                  {
                        //      now create the decompression stream based on the memory stream
                        using (BZip2InputStream decomp = new BZip2InputStream(rec))
                        {
                              decompressedBytes = new byte[decomp.Length];
                              decomp.Read(decompressedBytes, 0, (int)decomp.Length);
                        }      // the using statement ensures a flush, finalize and close
                  }

                  string strFinal = Encoding.ASCII.GetString(decompressedBytes);
                  Console.WriteLine("Decompressed string (base64)");
                  Console.WriteLine("[{0}]", strFinal);
                  Console.ReadLine();
            }
            private static void CheckFileExists()
            {
                  if (!File.Exists(FILE_PATH))
                        throw new FileNotFoundException("Could not find source file C:\test.txt");
            }
      }
}
0
 
AGBrownCommented:
Note that that has a few limitations due to the (int) casts from long for the stream lengths. To get around this, you would need to implement some kind of chunked read (and write), such as:
      byte[] data = new byte[4096];
      int size;
      do {
            size = inputStream.Read(data, 0, data.Length);
            //   now increment original array by size, and add data to the end
      } while (size > 0);

However, its likely you are really going to be using streams and not byte arrays, so that should be less of a problem.
0
VIDEO: THE CONCERTO CLOUD FOR HEALTHCARE

Modern healthcare requires a modern cloud. View this brief video to understand how the Concerto Cloud for Healthcare can help your organization.

 
Brian BushSolutions ArchitectAuthor Commented:
Works great!
The trick with the using() did the trick.

How big to do you think the file would have to be before it was effected by the int size?
I get the impression it would have to be huge.

I am going to open the inverse question now and will post the link in a sec.
--brian
0
 
Brian BushSolutions ArchitectAuthor Commented:
0
 
AGBrownCommented:
That's a tough one, but there is another quirk of that code that I just found in that if you put a small string into it "hello decompressed world", the output has a lot of spaces appended to the end of it. Similarly, I tried a large file and it did not come out the same, so I think it would be a good idea to do something about implementing chunked read/write methods if you are going to be using byte arrays and not streams.

The using is useful for anything that implements IDisposable, it ensures that you don't have to remember to call Close, or Finalize, etc.
0

Featured Post

Free Tool: Subnet Calculator

The subnet calculator helps you design networks by taking an IP address and network mask and returning information such as network, broadcast address, and host range.

One of a set of tools we're offering as a way of saying thank you for being a part of the community.

  • 3
  • 3
Tackle projects and never again get stuck behind a technical roadblock.
Join Now