Skip to main content

DevExpress v24.2 Update — Your Feedback Matters

Our What's New in v24.2 webpage includes product-specific surveys. Your response to our survey questions will help us measure product satisfaction for features released in this major update and help us refine our plans for our next major release.

Take the survey Not interested

How to: Add File to File Archive

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

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);
    }
}