NIlesh Lanke
NIlesh Lanke

Reputation: 1253

How to compress a file before saving on the disk?

I want to compress a file before saving physically on the disk.

I tried using compress and decompress methods (MSDN sample code) but all methods require a file which is already physically stored on the disk.

Upvotes: 7

Views: 3592

Answers (4)

Michał Kuliński
Michał Kuliński

Reputation: 1976

Use MemoryStream and GZipStream.

File is an array of bytes so you can try following code according to http://www.dotnetperls.com/compress :

using System;
using System.IO;
using System.IO.Compression;
using System.Text;

namespace ConsoleApplication1
{
    internal class Program
    {
        private static void Main(string[] args)
        {

            byte[] text = Encoding.ASCII.GetBytes(new string('X', 10000));
            byte[] compress = Compress(text);

            Console.WriteLine("Compressed");
            foreach (var b in compress)
            {
                Console.WriteLine("{0} ", b);
            }
            Console.ReadKey();
        }

        public static byte[] Compress(byte[] raw)
        {
            using (var memory = new MemoryStream())
            {
                using (var gzip = new GZipStream(memory, CompressionMode.Compress, true))
                {
                    gzip.Write(raw, 0, raw.Length);
                }
                return memory.ToArray();
            }
        }
    }
}

Upvotes: 0

Max
Max

Reputation: 7596

Can't you use the GZipStream class? It's stream based, so you shouldn't need an on-disk file to use this class.

Which kind of data are you trying to compress?

Upvotes: 0

dknaack
dknaack

Reputation: 60516

Description

You can use the GZipStream class not only with a fileName. It is possible to compress a Stream.

GZipStream Class Provides methods and properties used to compress and decompress streams.

Sample

System.IO.MemoryStream ms = new System.IO.MemoryStream();
System.IO.Compression.GZipStream sw = new System.IO.Compression.GZipStream(ms,
        System.IO.Compression.CompressionMode.Compress);
// now you can save the file to disc

More Information

Upvotes: 4

JaredPar
JaredPar

Reputation: 755269

The easiest way is to open the file as a Stream and wrap it with a compression API like GZipStream.

using (var fileStream = File.Open(theFilePath, FileMode.OpenOrCreate) {
  using (var stream = new GZipStream(fileStream, CompressionMode.Compress)) {
    // Write to the `stream` here and the result will be compressed
  }
}

Upvotes: 9

Related Questions