To combine the contents of a specific directory into a single ZIP file (archive), it is standard to use the CreateFromDirectory method of the System.IO.Compression.ZipFile class. Using this method allows you to complete the compression process with a single line of code, without having to write complex stream operations.
Implementation Sample: Backing Up a Documents Folder
In the following code, we create dummy files inside a specified folder (MyDocuments) and then compress the entire folder into a file named MyDocuments_Backup.zip.
Sample Code
Note: In environments like .NET Framework, you may need to add a reference to
System.IO.Compression.FileSystem.
using System;
using System.IO;
using System.IO.Compression; // Required for ZIP operations
public class Program
{
public static void Main()
{
// The folder to compress (source)
string sourceDir = "MyDocuments";
// The path for the created ZIP file (destination)
string zipPath = "MyDocuments_Backup.zip";
// 1. Prepare the test environment
// Create the folder and files beforehand
if (Directory.Exists(sourceDir)) Directory.Delete(sourceDir, recursive: true);
if (File.Exists(zipPath)) File.Delete(zipPath);
Directory.CreateDirectory(sourceDir);
File.WriteAllText(Path.Combine(sourceDir, "memo.txt"), "This is a meeting memo.");
File.WriteAllText(Path.Combine(sourceDir, "budget.csv"), "100,200,300");
try
{
Console.WriteLine($"Compressing folder '{sourceDir}'...");
// 2. Compress the folder to a ZIP file
// ZipFile.CreateFromDirectory(source directory, destination file path)
ZipFile.CreateFromDirectory(sourceDir, zipPath);
Console.WriteLine($"Compression complete: {Path.GetFullPath(zipPath)}");
}
catch (IOException ex)
{
// Occurs if a ZIP file with the same name already exists at the destination
Console.WriteLine($"Error: {ex.Message}");
}
}
}
Execution Result
Compressing folder 'MyDocuments'...
Compression complete: C:\Work\MyDocuments_Backup.zip
Explanation and Notes
1. Required Namespace
To use this feature, you must include using System.IO.Compression; at the top of your code.
2. Handling Duplicate Output Files
CreateFromDirectory throws an IOException if the destination ZIP file already exists. Since there is no built-in overwrite function, you should check for the file’s existence using File.Exists and delete it beforehand, or include a timestamp in the filename to ensure it is unique.
3. Character Encoding
In modern .NET (.NET Core / .NET 5 and later), UTF-8 encoding is used by default. This prevents character corruption even if Japanese filenames are included. If you need to force Shift-JIS for compatibility with standard Windows Explorer features in older environments, you must use an overloaded method that accepts a third argument for encoding.
