Showing posts with label unzip. Show all posts
Showing posts with label unzip. Show all posts

WP7 - Download zip file, unzip and save to isolated storage


  1. Create New "Windows Phone Application".
  2. Download "Silverlight SharpZipLib" from http://slsharpziplib.codeplex.com/releases/view/50561.
  3. Unpack "Silverlight SharpZipLib" and copy Bin/Release/SharpZipLib.WindowsPhone7.dll
  4. Create new folder "SharpZip" and past into copied SharpZipLib.WindowsPhone7.dll.
  5. Right click on project and "Add Reference...".
  6. Choose from "Browse" tab SharpZipLib.WindowsPhone7.dll from your project location.
  7. Add to "MainPage.xaml.cs" (probably you need to remove "using System.Windows.Shapes" because conflict System.Windows.Shapes.Path vs System.IO.Path):
    using System.IO;
    using System.IO.IsolatedStorage;
    using ICSharpCode.SharpZipLib.Zip;
    using ICSharpCode.SharpZipLib.Zip.Compression.Streams;
    
  8. Add code for download file from web:
    public MainPage()
    {
        InitializeComponent();
    
        Loaded += new RoutedEventHandler(MainPage_Loaded);
    }
    
    void MainPage_Loaded(object sender, RoutedEventArgs e)
    {
        System.Uri targetUri = new System.Uri("http://MyDomain/Archive.zip");
        HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(targetUri);
        //create asynchronous tast and declare callback to get data stream
        request.BeginGetResponse(new AsyncCallback(ReadWebRequestCallback), request);
    }
    
  9. And add function "ReadWebRequestCallback" to unzip & save file we got:
    private void ReadWebRequestCallback(IAsyncResult callbackResult)
    {
        HttpWebRequest myRequest = (HttpWebRequest)callbackResult.AsyncState;
        HttpWebResponse myResponse = (HttpWebResponse)myRequest.EndGetResponse(callbackResult);
        using (StreamReader httpwebStreamReader = new StreamReader(myResponse.GetResponseStream()))
        {
            //open isolated storage to save files
            using (IsolatedStorageFile isoStore = IsolatedStorageFile.GetUserStoreForApplication())
            {
                using (ZipInputStream s = new ZipInputStream(httpwebStreamReader.BaseStream))
                {
                    //s.Password = "123456";//if archive is encrypted
                    ZipEntry theEntry;
                    try
                    {
                        while ((theEntry = s.GetNextEntry()) != null)
                        {
                            string directoryName = Path.GetDirectoryName(theEntry.Name);
                            string fileName = Path.GetFileName(theEntry.Name);
    
                            // create directory
                            if (directoryName.Length > 0)
                            {
                                Directory.CreateDirectory(directoryName);
                            }
    
                            if (fileName != String.Empty)
                            {
                                //save file to isolated storage
                                using (BinaryWriter streamWriter = 
                                        new BinaryWriter(new IsolatedStorageFileStream(theEntry.Name,
                                            FileMode.OpenOrCreate, FileAccess.Write, FileShare.Write, isoStore)))
                                {
    
                                    int size = 2048;
                                    byte[] data = new byte[2048];
                                    while (true)
                                    {
                                        size = s.Read(data, 0, data.Length);
                                        if (size > 0)
                                        {
                                            streamWriter.Write(data, 0, size);
                                        }
                                        else
                                        {
                                            break;
                                        }
                                    }
                                }
    
                            }
                        }
                    }
                    catch (ZipException ze)
                    {
                        Debug.WriteLine(ze.Message);
                    }
                }
            }
    
        }
    }
    

  10. Run your application and enjoy.

Zip/Unzip files on iPhone/iPad/iOS


  1. Download ZipArchive from http://code.google.com/p/ziparchive/downloads/list.
  2. Drag into project.
  3. Add to project existing framework libz.1.2.3.dylib (last version).
  4. Import to project:
    #import "ZipArchive.h"
    
  5. Uncompress zip file example:
    NSString *documentsDirectory = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
    
    NSString *zipFilePath = [documentsDirectory stringByAppendingPathComponent:@"myZipFileName.zip"];
    
    NSString *output = [documentsDirectory stringByAppendingPathComponent:@"unZipDirName"];
    
    ZipArchive* za = [[ZipArchive alloc] init];
    
    if( [za UnzipOpenFile:zipFilePath] ) {
        if( [za UnzipFileTo:output overWrite:YES] != NO ) {
            //unzip data success
            //do something
        }
    
        [za UnzipCloseFile];
    }
    
    [za release];
    
  6. Compress directory or file example:
    BOOL isDir=NO;
    
    NSString *documentsDirectory = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
    
    NSArray *subpaths;
    
    NSString *toCompress = [NSString stringWithString:@"dirToZip_OR_fileNameToZip"];
    NSString *pathToCompress = [documentsDirectory stringByAppendingPathComponent:toCompress];
    
    NSFileManager *fileManager = [NSFileManager defaultManager]; 
    if ([fileManager fileExistsAtPath:pathToCompress isDirectory:&isDir] && isDir){
        subpaths = [fileManager subpathsAtPath:pathToCompress];
    } else if ([fileManager fileExistsAtPath:pathToCompress]) {
        subpaths = [NSArray arrayWithObject:pathToCompress];
    }
    
    NSString *zipFilePath = [documentsDirectory stringByAppendingPathComponent:@"myZipFileName.zip"];
      
    ZipArchive *za = [[ZipArchive alloc] init];
    [za CreateZipFile2:zipFilePath];
    if (isDir) {
        for(NSString *path in subpaths){  
            NSString *fullPath = [pathToCompress stringByAppendingPathComponent:path];
            if([fileManager fileExistsAtPath:fullPath isDirectory:&isDir] && !isDir){
                [za addFileToZip:fullPath newname:path];  
            }
        }
    } else {
        [za addFileToZip:pathToCompress newname:toCompress];
    }
    
    BOOL successCompressing = [archiver CloseZipFile2];