Write compressed files to the disk. You may have a web app that needs to save data efficiently such as in compressed log files. Develop a utility method that uses the reliable framework methods to persist GZIP-compressed strings.
Here we will use the .NET framework's built-in methods. It provides these new methods because compression and decompression using GZIP is an extremely common problem in any programming language, and is widely used on the Internet.
| Object | Use |
| byte[] array | Contains single bytes. In C#, chars are 2 bytes. |
| FileStream | Streams in C# can be used as filters or storage. We use FileStream for storage. |
| GZipStream | Filters data. Has these options: • CompressionMode.Compress • CompressionMode.Decompress |
The following methods compress strings to disk. GZipStream requires bytes. We can use the File static methods to write to temporary files. You see several useful framework methods. Remember to add System.IO.Compression at the top.
using System.IO;
using System.IO.Compression;
using System.Text;
class Program
{
static void Main()
{
try
{
//
// 1.
// Starting file is 26,747 bytes.
//
string anyString = File.ReadAllText("TextFile1.txt");
//
// 2.
// Output file is 7,388 bytes.
//
CompressStringToFile("new.gz", anyString);
}
catch
{
//
// Couldn't compress.
//
}
//
// 3.
// In Explorer, open with 7-Zip.
// File is 26,747 bytes.
//
}
public static void CompressStringToFile(string fileName, string value)
{
//
// A.
// Write string to temporary file.
//
string temp = Path.GetTempFileName();
File.WriteAllText(temp, value);
//
// B.
// Read file into byte array buffer.
//
byte[] b;
using (FileStream f = new FileStream(temp, FileMode.Open))
{
b = new byte[f.Length];
f.Read(b, 0, (int)f.Length);
}
//
// C.
// Use GZipStream to write compressed bytes to target file.
//
using (FileStream f2 = new FileStream(fileName, FileMode.Create))
using (GZipStream gz = new GZipStream(f2, CompressionMode.Compress, false))
{
gz.Write(b, 0, b.Length);
}
}
}Yes. I have used it in a deployed application with no problems. It however can be slow so if you are working on a program with extremely strict performance requirements, don't use this code.
This article used to have an example that was incorrect. It was tested but had an encoding and decompression problem. Dot Net Perls apologizes for this mistake and thanks Jon for his bug report.
More complex methods are available for compression and this example alone does not most requirements. For the best compression ratio, going outside the .NET framework and embedding 7-Zip or another open source program would be excellent. See an example of that.