Back to Devexpress

How to: Add File to File Archive

officefileapi-119014-zip-compression-and-archive-api-examples-how-to-add-file-to-file-archive.md

latest1.9 KB
Original Source

How to: Add File to File Archive

  • Sep 19, 2023

When the file archive is opened with the ZipArchive.Read method, you cannot save it to the same file. The ZipArchive.Save method attempts to overwrite the locked file resulting in an exception.

This code snippet illustrates how you can add a file to an archive and save it with the same name as before.

View Example

csharp
public void AddFileToArchive() {
    MemoryStream stream = new MemoryStream();
    string[] sourcefiles = this.sourceFiles;
    string pathToZipArchive = "Documents\\Example.zip";

    using (FileStream fs = File.Open(pathToZipArchive, FileMode.Open)) {
        fs.CopyTo(stream);
        fs.Close();
    }
    stream.Seek(0, SeekOrigin.Begin);
    using (ZipArchive archive = ZipArchive.Read(stream, System.Text.Encoding.Default, false)) {
        foreach (string sfile in sourcefiles) {
            archive.AddFile(sfile, "/");
        }
        archive.Save(pathToZipArchive);
    }
}
vb
Public Sub AddFileToArchive()
    Dim stream As New MemoryStream()
    Dim sourcefiles() As String = Me.sourceFiles
    Dim pathToZipArchive As String = "Documents\Example.zip"

    Using fs As FileStream = File.Open(pathToZipArchive, FileMode.Open)
        fs.CopyTo(stream)
        fs.Close()
    End Using
    stream.Seek(0, SeekOrigin.Begin)
    Using archive As ZipArchive = ZipArchive.Read(stream, System.Text.Encoding.Default, False)
        For Each sfile As String In sourcefiles
            archive.AddFile(sfile, "/")
        Next sfile
        archive.Save(pathToZipArchive)
    End Using
End Sub