C# Compression Algorithms: Implementation and Applications

C# Compression Algorithms: From Basics to Practice

Hello everyone! Today, let’s talk about file compression algorithms in C#. Compression algorithms are very important in actual development, whether it’s to reduce file size, optimize network transmission, or perform data backup, they are indispensable. Let’s explore how to implement compression algorithms in C# and their practical application scenarios.

Basic Knowledge: System.IO.Compression

In C#, we mainly use the classes provided by the <span>System.IO.Compression</span> namespace to implement compression functionality. This namespace can be used directly in .NET Core 3.1 and above without the need to install additional NuGet packages.

using System;

using System.IO;

using System.IO.Compression;


class Program
{
    static void Main()
    {
        // Create a simple string to compress
        string originalText = "Hello, this is a piece of text that needs to be compressed!" * 1000;
        byte[] compressed = CompressString(originalText);
        
        Console.WriteLine($"Original size: {originalText.Length} bytes");
        Console.WriteLine($"Compressed size: {compressed.Length} bytes");
    }
}
C#

GZip Compression Implementation

GZip is one of the most commonly used compression algorithms, achieving a good balance between compression ratio and performance.

public static byte[] CompressString(string text)
{
    var bytes = Encoding.UTF8.GetBytes(text);
    using var msi = new MemoryStream(bytes);
    using var mso = new MemoryStream();
    using (var gs = new GZipStream(mso, CompressionMode.Compress))
    {
        msi.CopyTo(gs);
    }
    return mso.ToArray();
}

public static string DecompressString(byte[] compressed)
{
    using var msi = new MemoryStream(compressed);
    using var mso = new MemoryStream();
    using (var gs = new GZipStream(msi, CompressionMode.Decompress))
    {
        gs.CopyTo(mso);
    }
    return Encoding.UTF8.GetString(mso.ToArray());
}
C#

Tip: Use <span>using</span> statements to ensure resources are released properly to avoid memory leaks.

ZIP File Operations

In actual projects, we often need to handle ZIP files. Here is a simple example:

public static void CreateZipFile(string sourceDirectory, string zipPath)
{
    try
    {
        ZipFile.CreateFromDirectory(sourceDirectory, zipPath, 
            CompressionLevel.Optimal, false);
        Console.WriteLine($"Successfully created ZIP file: {zipPath}");
    }
    catch (Exception ex)
    {
        Console.WriteLine($"Failed to create ZIP file: {ex.Message}");
    }
}
C#

Performance Optimization Tips:

  • For large files, it’s recommended to use buffered read/write

  • You can balance the compression ratio and performance by setting <span>CompressionLevel</span>

  • Consider using parallel compression to improve efficiency

Practical Application Scenarios

  1. Website File Packaging:
public async Task BackupWebsite(string webRoot, string backupPath)
{
    await Task.Run(() => 
    {
        CreateZipFile(webRoot, backupPath);
    });
}
C#
  1. Log File Compression:
public class LogCompressor
{
    public void CompressLogs(string logDirectory)
    {
        var files = Directory.GetFiles(logDirectory, "*.log");
        foreach (var file in files)
        {
            CompressFile(file, file + ".gz");
            File.Delete(file);
        }
    }
}
C#

Unit Test Example

[TestClass]
public class CompressionTests
{
    [TestMethod]
    public void TestStringCompression()
    {
        string original = "Test data" * 100;
        var compressed = CompressString(original);
        var decompressed = DecompressString(compressed);
        
        Assert.AreEqual(original, decompressed);
        Assert.IsTrue(compressed.Length < original.Length * 2);
    }
}
C#

Friends, today’s C# learning journey ends here! Remember to code along, and feel free to ask questions in the comments. Wishing everyone happy learning, may your C# development path be ever-expanding! Code changes the world, see you next time!

Leave a Comment