.NET 8 Preview 6 CreateFromDirectory using Stream

Introduction

On 07/11/2023, the .NET 8 Preview 6 was launched with a new overload for the ZipFile, CreateFromDirectory method.

.NET 8 Preview 6 CreateFromDirectory

Now it's possible to use a stream to compress files from a directory without caching them in a temporary file. Now we can manage the compression result directly in the memory.

The basic usage example.

ZipFile.CreateFromDirectory(
    sourceDirectoryName: "/path/filesToCompress",
    destination: stream,
    compressionLevel: CompressionLevel.Fastest,
    includeBaseDirectory: true,
    entryNameEncoding: Encoding.UTF8);

The stream variable we can create is like this.

Stream stream = new MemoryStream();

And transform in a byte array.

using var memoryStream = new MemoryStream();
stream.Position = 0;
stream.CopyTo(memoryStream);
var fileBytes = memoryStream.ToArray();

Here's a working example of reading and saving a directory on a Table in Microsoft SqlServer. Add this code to a console app in Program.cs file using a .NET 8 Preview 6 SDK (minimum).

using System.Data.SqlClient;
using System.IO.Compression;
using System.Text;

string connectionString = "Data Source=localhost;Initial Catalog=MyCatalog;Integrated Security=SSPI;";

Stream stream = new MemoryStream();

Console.WriteLine("Compressing...");

ZipFile.CreateFromDirectory(
    sourceDirectoryName: "C:\\MyLocalFiles",
    destination: stream,
    compressionLevel: CompressionLevel.Fastest,
    includeBaseDirectory: true,
    entryNameEncoding: Encoding.UTF8);

using var connection = new SqlConnection(connectionString);

Console.WriteLine("Openning DB Connection...");

connection.Open();

string sqlQuery = "INSERT INTO MyTable (MyFieldStreamData) VALUES (@StreamData)";

using var command = new SqlCommand(sqlQuery, connection);

var parameter = new SqlParameter("@StreamData", System.Data.SqlDbType.VarBinary);
 
using var memoryStream = new MemoryStream();

stream.Position = 0;
stream.CopyTo(memoryStream);
var fileBytes = memoryStream.ToArray();

parameter.Value = fileBytes;

command.Parameters.Add(parameter);
Console.WriteLine("Writing on DB...");

command.ExecuteNonQuery();
Console.WriteLine("Press any key...");

Console.ReadKey();

To try this example, you need to create a table using this code:

CREATE TABLE [dbo].[MyTable](
	[MyFieldStreamData] [varbinary](max) NOT NULL
) 

It's supported to use other Stream classes from C#.