Creating a compression tool with c# in seconds

Creating a compression tool involves using a compression algorithm and implementing it in a programming language. One common algorithm is the Deflate algorithm, which is used in the ZIP file format. In C#, you can use the `System.IO.Compression` namespace, which provides classes for compressing and decompressing streams.


Here's a simple example of a compression tool in C# using the Deflate algorithm:


 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
using System;
using System.IO;
using System.IO.Compression;

class Program
{
    static void Main()
    {
        Console.WriteLine("Enter the path of the file to compress:");
        string filePath = Console.ReadLine();

        // Compress the file
        CompressFile(filePath);

        Console.WriteLine("Compression completed.");

        Console.WriteLine("Enter the path of the compressed file to decompress:");
        string compressedFilePath = Console.ReadLine();

        // Decompress the file
        DecompressFile(compressedFilePath);

        Console.WriteLine("Decompression completed.");
    }

    static void CompressFile(string filePath)
    {
        using (FileStream originalFileStream = File.OpenRead(filePath))
        {
            using (FileStream compressedFileStream = File.Create(filePath + ".gz"))
            {
                using (GZipStream compressionStream = new GZipStream(compressedFileStream, CompressionMode.Compress))
                {
                    originalFileStream.CopyTo(compressionStream);
                }
            }
        }
    }

    static void DecompressFile(string compressedFilePath)
    {
        using (FileStream compressedFileStream = File.OpenRead(compressedFilePath))
        {
            string decompressedFilePath = compressedFilePath.Replace(".gz", "_decompressed.txt");

            using (FileStream decompressedFileStream = File.Create(decompressedFilePath))
            {
                using (GZipStream decompressionStream = new GZipStream(compressedFileStream, CompressionMode.Decompress))
                {
                    decompressionStream.CopyTo(decompressedFileStream);
                }
            }

            Console.WriteLine($"Decompressed file saved at: {decompressedFilePath}");
        }
    }
}

This example uses the GZipStream class for compression and decompression. Note that this is a simple example, and in a real-world scenario, you might want to add error handling and better user interaction. Also, keep in mind that the effectiveness of compression depends on the type of data you're working with.

Comments

Popular posts from this blog

Securing Your ASP.NET Core Blazor App

Creating a website with strong SEO

Web3 in a couple words explained