Creating an In Memory Zip Archive for multiple files in C#

Standard

I was asked an interesting technical question the other day that felt relevant enough to share. Having tackled a similar issue in the distant past using SharpLib this felt like a good opportunity to recreate the functionality using native .Net functionality in the form of ZipArchive!

For this use case the ask was to store various string data that can be appended to an in memory zip archive in form of a new file containing the data. After the data is processed the desire was to write the zip file to a specific location for another process. The following is short proof of concept to outline the implementation.

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

namespace ZipTest
{
    internal class Program
    {
        /// <summary>
        /// Create a new file to contain the data passed in and then add that to the Zip Archive
        /// </summary>
        /// <param name="archive">The Archive to append to</param>
        /// <param name="fileName">The name of the file as you wish it to appear in the archive</param>
        /// <param name="textContent"></param>
        static void AddFileToZip(ZipArchive archive, string fileName, string textContent)
        {
            // Create a new entry in the archive using the specified file name
            ZipArchiveEntry entry = archive.CreateEntry(fileName);

            // Write the text content to the entry
            using (Stream entryStream = entry.Open())
            using (StreamWriter writer = new StreamWriter(entryStream, Encoding.UTF8))
            {
                writer.Write(textContent);
            }
        }
        // Append the data in the form of a file to the archive
        static void AppendFileToZipArchive(MemoryStream zipStream, string fileName, string textContent)
        {
            // Create a new ZipArchive instance using the existing MemoryStream
            using (ZipArchive archive = new ZipArchive(zipStream, ZipArchiveMode.Update, leaveOpen: true))
            {
                AddFileToZip(archive, fileName, textContent);
            }
        }

        static void SaveZipArchiveToDisk(MemoryStream zipArchiveStream, string outputPath)
        {
            // Save the MemoryStream to a file
            File.WriteAllBytes(outputPath, zipArchiveStream.ToArray());
        }
        static void Main(string[] args)
        {
            using (MemoryStream zipArchiveStream = new MemoryStream())
            {
                // Append files to the zip archive
                AppendFileToZipArchive(zipArchiveStream, "file1.txt", "This is the content of file 1.");
                AppendFileToZipArchive(zipArchiveStream, "file2.txt", "This is the content of file 2.");

                // Save the zip archive to a file
                SaveZipArchiveToDisk(zipArchiveStream, "result.zip");
            }
        }
    }
}

Hopefully you find this useful!

Javascript: Var vs Let vs Const?

Standard

In JavaScript, var, let, and const are used to declare variables, but they have different scoping rules and behaviors. Here’s a breakdown of the differences between them:

  1. var:
    • Variables declared with var are function-scoped or globally scoped, depending on where they are declared. They are not block-scoped.
    • This means that a variable declared with var is accessible throughout the entire function in which it is declared or throughout the global scope if declared outside of any function.
    • var declarations are hoisted to the top of their scope during the compilation phase, so you can access them before they are declared in your code (this can lead to unexpected behavior).
    • var variables can be re-declared and updated within their scope.
  2. let:
    • Variables declared with let are block-scoped, which means they are confined to the nearest enclosing block, such as a loop or an if statement.
    • let variables are not hoisted to the top of their block. They are only accessible after they are declared in the code.
    • Unlike var, you cannot re-declare a variable using let in the same scope.
    • let variables can be updated after declaration, meaning you can change their value.
  3. const:
    • Variables declared with const are also block-scoped like let.
    • However, const variables are constants, which means their value cannot be reassigned after it’s assigned once. This makes them suitable for values that should remain constant throughout their scope.
    • Like let, const variables are not hoisted and are only accessible after they are declared in the code.
    • Similar to let, you cannot re-declare a variable using const in the same scope.

Here’s a quick example to illustrate the differences:

function example() {
    var varVariable = "I am var";
    let letVariable = "I am let";
    const constVariable = "I am const";

    if (true) {
        var varVariable = "I am still var";
        let letVariable = "I am still let"; // This creates a new block-scoped variable
        // const constVariable = "This will cause an error"; // Cannot redeclare in the same scope
    }

    console.log(varVariable); // Outputs: "I am still var"
    console.log(letVariable); // Outputs: "I am let"
    console.log(constVariable); // Outputs: "I am const"
}

example();

In modern JavaScript, it’s generally recommended to use let and const over var due to their more predictable scoping and behavior. Use let when you need to reassign a variable, and use const when you want to ensure a variable’s value remains constant.