Home > View Post

Cracking open Zip files in Silverlight Beta 1

I've not had as much time to play with Silverlight 2 since Beta 1 than I would have liked, though I'm planning to make that up shortly. In the meantime I ran into a small shock when trying to use the Downloader from 1.1 Alpha in to download and open a Zip file. Change is for heroes.

The whole API for cracking open ZIP files has changed but fortunately, this scenario is still supported. The Downloader was deprecated (though still supported via Javascript for 1.0 compatibility I believe) in favour of the new WebClient.

Here's an example of how you might download an image contained in a zip and add it to your page:

private void ButtonClicked(object sender, HtmlEventArgs args)
{
    WebClient imageDownloader = new WebClient();
    imageDownloader.OpenReadCompleted += new OpenReadCompletedEventHandler(imageDownloader_OpenReadCompleted);
    imageDownloader.OpenReadAsync(new Uri("/test.zip", UriKind.Relative));
}

void imageDownloader_OpenReadCompleted(object sender, OpenReadCompletedEventArgs e)
{
    StreamResourceInfo zipInfo = new StreamResourceInfo((Stream)e.Result, null);
    StreamResourceInfo imgInfo = Application.GetResourceStream(zipInfo, new Uri("test.bmp", UriKind.Relative));

    BitmapImage source = new BitmapImage();
    source.SetSource(imgInfo.Stream);
    Image img = new Image();
    img.Source = source;
    panel.Children.Add(img);
}

Where the img is called test.bmp in the root of the test.zip file. Here's another example should you wish to access a text file inside the zip:

private void ButtonClicked(object sender, HtmlEventArgs args)
{
    WebClient txtDownloader = new WebClient();
    txtDownloader.OpenReadCompleted += new OpenReadCompletedEventHandler(txtDownloader_OpenReadCompleted);
    txtDownloader.OpenReadAsync(new Uri("/test.zip", UriKind.Relative));
}

void txtDownloader_OpenReadCompleted(object sender, OpenReadCompletedEventArgs e)
{
    StreamResourceInfo zipPackageSri = new StreamResourceInfo((Stream)e.Result, null);
    StreamResourceInfo textSri = Application.GetResourceStream(zipPackageSri, new Uri("test.txt", UriKind.Relative));

    using (StreamReader sr = new StreamReader(textSri.Stream))
    {
        TextBlock txt = new TextBlock() { Text = sr.ReadToEnd() };
        panel.Children.Add(txt);
    }
}

And here's an image showing the contents of my zip and the contents of test.txt in notepad:

Hello Readers inside test.txt

And the resulting Silverlight wonder:

Hello Readers inside Silverlight

Tags: Silverlight

 
Josh Post By Josh Twist
11:32 AM
06 May 2008

» Next Post: Using Ukadc.Diagnostics with existing TraceSources
« Previous Post: Using the SqlTraceListener with Enterprise Library Logging

Comments are closed for this post.

© 2005 - 2017 Josh Twist - All Rights Reserved.