Search code examples
c#zipwin-universal-app

Extracting specific File from archive in UWP


To save space I have zipped my books(in xml format) in my UWP Project. I want to Extract a file to my Local Folder based upon it's name.

Till Now what I have done(This extracts all files) :

ZipFile.ExtractToDirectory(sourceCompressedFile.Path, destinationFolder.Path);

However this extracts all the files from my archive to my destination folder. I know this could be a trivial task using SharpZipLib but this is an inbuilt method and would help me reduce my app size . I simply want to extract a file whose name matches with a name I provide. There are three methods other than this but I lost my way using them.

This can be done easily using DotNetZip as seen here but I don't want to use any third party Library


Solution

  • I think you have several files zipped in one zip archive, so will the ZipFile.ExtractToDirectory Method (String, String) extract all the files in the specified zip archive to a directory.

    If you just want to access one special file in this zipped archive, you can use ZipArchiveEntry Class to achieve this work, for example here:

    StorageFolder _folder = await Windows.ApplicationModel.Package.Current.InstalledLocation.GetFolderAsync("Assets");
    /*fails here FileNotFound*/
    StorageFile sourceCompressedFile = await _folder.GetFileAsync("archived.zip");
    
    StorageFolder folder = ApplicationData.Current.LocalFolder;
    
    // ZipFile.ExtractToDirectory(file.Path, folder.Path);
    
    using (ZipArchive archive = ZipFile.OpenRead(sourceCompressedFile.Path))
    {
        foreach (ZipArchiveEntry entry in archive.Entries)
        {
            if (entry.FullName.ToString() == "miao2.jpg")
            {
                entry.ExtractToFile(Path.Combine(folder.Path, entry.FullName));
            }
        }
    }
    

    I zipped several pictures as the "archived.zip" file for test, in this sample, it will only extract the image file named "miao2.jpg".