Share via

Archive Folder content in C# 10

Alin A 25 Reputation points
2026-03-07T09:22:46.6966667+00:00

Hi,

I want to implement two functions a synchronous and non synchronous in C# 10 that receives the following parameters:

1.A string representing the valid archive file path, including the file name and extension.

The supported archive formats are: ZIP, TAR, TGZ, GZ, BZ2, XZ, 7Z, and RAR.

2.A string representing a valid folder path that contains files and/or subfolders.

The function should create a new archive file containing all the files and subfolders from the specified folder.

The archive format should be determined by the file extension of the archive file path provided in the first parameter.

After the archive is created successfully, all other files and folders inside the output folder should be deleted, leaving only the newly created archive file.

Finally, the function should return a Boolean value indicating whether the operation succeeded or failed.

If not all archive formats supported by Microsoft, please give me references from where I can use them.

Thanks in advance,

Developer technologies | C#
Developer technologies | C#

An object-oriented and type-safe programming language that has its roots in the C family of languages and includes support for component-oriented programming.

0 comments No comments
{count} votes

2 answers

Sort by: Most helpful
  1. Danny Nguyen (WICLOUD CORPORATION) 6,455 Reputation points Microsoft External Staff Moderator
    2026-03-09T07:35:54.01+00:00

    Hi @Alin A .

    In C# 10 you’re typically on .NET 6, so it’s important to separate:

    1. What .NET supports

    Built-in (BCL):

    • .zip: System.IO.Compression (ZipFile, ZipArchive)
    • .gz: GZipStream (compression only, not a multi-file “folder archive”)

    Not built-in in .NET 6:

    • .tar / .tgz, .bz2, .xz, .7z, .rar (RAR creation in particular is usually not available)

    Also note: GZ/BZ2/XZ are compression formats, not container archives. If you want “folder -> single file”, you normally use TAR + compression (e.g. folder.tar.gz aka .tgz), or ZIP/7Z.

    2. If you need many formats: use a library

    A common choice is SharpCompress (NuGet). It can create ZIP/TAR and compress with GZip/BZip2/XZ, and supports 7z (RAR is typically extract-only, not create).

    If the requirement is “must be able to create .rar”, you’ll likely need an external tool (WinRAR/rar.exe) and appropriate licensing, because most .NET libraries do not generate RAR archives.

    3. Minimal working implementation for ZIP (sync + async)

    Below creates the archive, then deletes everything else in the output directory (the directory containing archiveFilePath), leaving only the archive. It writes to a temp file first so you don’t accidentally delete the archive while it’s being created.

    
    using System.IO.Compression;
    
    public static class Archiver
    
    {
    
        public static bool ArchiveFolder(string archiveFilePath, string sourceFolderPath)
    
        {
    
            try
    
            {
    
                var ext = Path.GetExtension(archiveFilePath);
    
                if (!ext.Equals(".zip", StringComparison.OrdinalIgnoreCase))
    
                    throw new NotSupportedException("Only .zip is supported by this in-box example.");
    
                Directory.CreateDirectory(Path.GetDirectoryName(archiveFilePath)!);
    
                var temp = Path.Combine(Path.GetTempPath(), Guid.NewGuid() + ".zip");
    
                ZipFile.CreateFromDirectory(sourceFolderPath, temp, CompressionLevel.Optimal, includeBaseDirectory: false);
    
                File.Move(temp, archiveFilePath, overwrite: true);
    
                CleanDirectoryExceptFile(Path.GetDirectoryName(archiveFilePath)!, archiveFilePath);
    
                return true;
    
            }
    
            catch
    
            {
    
                return false;
    
            }
    
        }
    
        public static async Task<bool> ArchiveFolderAsync(string archiveFilePath, string sourceFolderPath, CancellationToken ct = default)
    
        {
    
            try
    
            {
    
                var ext = Path.GetExtension(archiveFilePath);
    
                if (!ext.Equals(".zip", StringComparison.OrdinalIgnoreCase))
    
                    throw new NotSupportedException("Only .zip is supported by this in-box example.");
    
                Directory.CreateDirectory(Path.GetDirectoryName(archiveFilePath)!);
    
                var temp = Path.Combine(Path.GetTempPath(), Guid.NewGuid() + ".zip");
    
                await Task.Run(() =>
    
                {
    
                    ct.ThrowIfCancellationRequested();
    
                    ZipFile.CreateFromDirectory(sourceFolderPath, temp, CompressionLevel.Optimal, includeBaseDirectory: false);
    
                }, ct);
    
                File.Move(temp, archiveFilePath, overwrite: true);
    
                CleanDirectoryExceptFile(Path.GetDirectoryName(archiveFilePath)!, archiveFilePath);
    
                return true;
    
            }
    
            catch
    
            {
    
                return false;
    
            }
    
        }
    
        private static void CleanDirectoryExceptFile(string directoryPath, string keepFilePath)
    
        {
    
            var keepFull = Path.GetFullPath(keepFilePath);
    
            foreach (var file in Directory.EnumerateFiles(directoryPath))
    
            {
    
                if (!Path.GetFullPath(file).Equals(keepFull, StringComparison.OrdinalIgnoreCase))
    
                    File.Delete(file);
    
            }
    
            foreach (var dir in Directory.EnumerateDirectories(directoryPath))
    
            {
    
                Directory.Delete(dir, recursive: true);
    
            }
    
        }
    
    }
    
    

    To support .tar, .tgz, .bz2, .xz, .7z, etc., you can implement the same “temp then move + clean” pattern, but swap out the archive writer with SharpCompress (or another archiving library).

    I hope this helps.

    If you found my response helpful or informative, I would greatly appreciate it if you could follow this guidance provide feedback. Thank you. 


  2. Q&A Assist
    2026-03-07T09:23:04.47+00:00
    AI generated content. This question contains an answer created with AI from Q&A Assist. Learn more

    For .NET/C# the built-in support is for ZIP archives via System.IO.Compression. Other formats (TAR, TGZ, GZ, BZ2, XZ, 7Z, RAR) require third‑party libraries.

    Below is an example of how to implement synchronous and asynchronous methods for ZIP using the ZipFile APIs, plus guidance for other formats.

    using System;
    using System.IO;
    using System.IO.Compression;
    using System.Threading;
    using System.Threading.Tasks;
    
    public static class FolderArchiver
    {
        public static bool ArchiveFolder(string archivePath, string sourceFolder)
        {
            try
            {
                // Validate inputs
                if (string.IsNullOrWhiteSpace(archivePath)) return false;
                if (string.IsNullOrWhiteSpace(sourceFolder)) return false;
                if (!Directory.Exists(sourceFolder)) return false;
    
                // Ensure output directory exists
                Directory.CreateDirectory(Path.GetDirectoryName(archivePath)!);
    
                // ZIP only in this example
                if (!archivePath.EndsWith(".zip", StringComparison.OrdinalIgnoreCase))
                    throw new NotSupportedException("Only .zip is supported by built-in APIs.");
    
                // ZipFile.CreateFromDirectory requires that the archive does not exist
                if (File.Exists(archivePath))
                    File.Delete(archivePath);
    
                ZipFile.CreateFromDirectory(sourceFolder, archivePath);
    
                // Delete everything else in the output folder except the archive
                CleanupOutputFolder(Path.GetDirectoryName(archivePath)!, archivePath);
    
                return true;
            }
            catch
            {
                return false;
            }
        }
    
        public static async Task<bool> ArchiveFolderAsync(
            string archivePath,
            string sourceFolder,
            CancellationToken cancellationToken = default)
        {
            try
            {
                if (string.IsNullOrWhiteSpace(archivePath)) return false;
                if (string.IsNullOrWhiteSpace(sourceFolder)) return false;
                if (!Directory.Exists(sourceFolder)) return false;
    
                Directory.CreateDirectory(Path.GetDirectoryName(archivePath)!);
    
                if (!archivePath.EndsWith(".zip", StringComparison.OrdinalIgnoreCase))
                    throw new NotSupportedException("Only .zip is supported by built-in APIs.");
    
                if (File.Exists(archivePath))
                    File.Delete(archivePath);
    
                // Async ZIP creation using ZipFile.CreateFromDirectoryAsync
                await ZipFile.CreateFromDirectoryAsync(
                    sourceFolder,
                    archivePath,
                    cancellationToken);
    
                CleanupOutputFolder(Path.GetDirectoryName(archivePath)!, archivePath);
    
                return true;
            }
            catch
            {
                return false;
            }
        }
    
        private static void CleanupOutputFolder(string outputFolder, string archivePath)
        {
            var archiveFullPath = Path.GetFullPath(archivePath);
    
            // Delete files except the archive
            foreach (var file in Directory.GetFiles(outputFolder))
            {
                var full = Path.GetFullPath(file);
                if (!string.Equals(full, archiveFullPath, StringComparison.OrdinalIgnoreCase))
                {
                    File.Delete(file);
                }
            }
    
            // Delete subdirectories
            foreach (var dir in Directory.GetDirectories(outputFolder))
            {
                Directory.Delete(dir, recursive: true);
            }
        }
    }
    

    Key points from the APIs used:

    • ZipFile.CreateFromDirectory synchronously creates a zip archive from a directory. The archive must not already exist; if it does, it must be deleted first.
    • ZipFile.CreateFromDirectoryAsync provides asynchronous creation with overloads that accept just source/destination and a CancellationToken, or also CompressionLevel, includeBaseDirectory, and optional Encoding.
    • Both synchronous and asynchronous methods preserve directory structure and will throw if a file cannot be added, leaving the archive invalid.

    Example async overloads (from the API) you can choose from:

    // Simplest async overload
    Task ZipFile.CreateFromDirectoryAsync(
        string sourceDirectoryName,
        string destinationArchiveFileName,
        CancellationToken cancellationToken = default);
    
    // With compression level and includeBaseDirectory
    Task ZipFile.CreateFromDirectoryAsync(
        string sourceDirectoryName,
        string destinationArchiveFileName,
        CompressionLevel compressionLevel,
        bool includeBaseDirectory,
        CancellationToken cancellationToken = default);
    

    For streaming scenarios (e.g., writing to a Stream instead of a file), there are corresponding async overloads that take a Stream as destination.

    Support for other archive formats

    • Built-in .NET APIs in System.IO.Compression and ZipFile cover ZIP only.
    • TAR, TGZ, GZ, BZ2, XZ, 7Z, and RAR are not supported by the standard .NET libraries shown in the context. These require third‑party libraries (for example, libraries that wrap 7-Zip or provide TAR/GZip support) or external tools.
    • In Azure DevOps Pipelines, the ArchiveFiles@2 task supports multiple formats (zip, 7z, tar, wim, and compressed tar variants like .tar.gz, .tar.bz2, .tar.xz), but that is a pipeline task, not a .NET API.

    To extend the example to multiple formats in a C# library, a typical pattern is:

    • Switch on Path.GetExtension(archivePath).ToLowerInvariant().
    • For .zip, use ZipFile.CreateFromDirectory / CreateFromDirectoryAsync as above.
    • For other extensions, call into the appropriate third‑party library or external tool.

    References:

    0 comments No comments

Your answer

Answers can be marked as 'Accepted' by the question author and 'Recommended' by moderators, which helps users know the answer solved the author's problem.