Back to Devexpress

How to: Archive Selected Files

officefileapi-15240-zip-compression-and-archive-api-examples-how-to-archive-selected-files.md

latest2.3 KB
Original Source

How to: Archive Selected Files

  • Sep 19, 2023
  • 2 minutes to read

To archive selected files create a ZipArchive class instance and call its AddFile method for each selected file.

To store a file without its path, call the ZipArchive.AddFile method with the “/“ parameter. The file is placed in the root node of the archive. Call the ZipArchive.Save method. The archive is created and saved to a specified location.

This code snippet creates a new archive and add files with .txt and .docx extensions to the archive root. The ZipArchive.Save method compresses data and saves the archive to a file.

View Example

csharp
using DevExpress.Compression;

public void ArchiveFiles() {

    // In this example, this.SourceFiles returns
    // file names from the Documents folder
    // in the working directory
    string[] sourcefiles = this.sourceFiles;
    string[] ext = new string[] {".txt", ".docx"};
    using (ZipArchive archive = new ZipArchive()) {
        foreach (string file in sourcefiles) {
            if (ext.Contains(Path.GetExtension(file)))
            archive.AddFile(file, "/");
        }
        archive.Save("Documents\\ArchiveFiles.zip");
    }
}
vb
Imports DevExpress.Compression

Public Sub ArchiveFiles()
    ' In this example, this.SourceFiles returns
    ' file names from the Documents folder
    ' in the working directory
    Dim sourcefiles() As String = Me.sourceFiles
    Dim ext() As String = {".txt", ".docx"}
    Using archive As New ZipArchive()
        For Each file As String In sourcefiles
            If ext.Contains(Path.GetExtension(file)) Then
            archive.AddFile(file, "/")
            End If
        Next file
        archive.Save("Documents\ArchiveFiles.zip")
    End Using
End Sub