Reading zip files from Silverlight

Silverlight doesn't have any classes from the System.IO.Compression namespace, but it's gone something better, Application.GetResourceStream.  It's pretty easy to take a stream to a zp file and get a stream to one of the uncomressed files inside it:

StreamResourceInfo zipInfo = new StreamResourceInfo(zipStream, null);
StreamResourceInfo streamInfo = Application.GetResourceStream(zipInfo, new Uri(fileName, UriKind.Relative));
Stream fileStream = streamInfo.Stream;

All you need to do is provide the stream to the zip file, and the name of the file you want to extract, and in three lines of code you have a stream to the uncompressed file. But there's one snag: What if you don't know the name of the file(s) inside the zip file? There is no api to browse through the contents of the zip file. A common workaround is to include a manifest file in the zip which lists the contents of the zip archive, but for some, this isn't possible because they don't conrol the creation of the content, and are just consuming it. It's actually not too hard to list the files in a zip archive, with a little help from the zip file format specification I wrote a little utility method that lists the files contained in a zip file. Its usage should be straightforward.


public class ZipUtil

/// <summary>
/// Reads the file names from the header of the zip file
/// </summary>
/// <param name="zipStream">The stream to the zip file</param>
/// <returns>An array of file names stored within the zip file. These file names may also include relative paths.</returns>
public static string[] GetZipContents(System.IO.Stream zipStream)

List<string> names = new List<string>();
BinaryReader reader = new BinaryReader(zipStream);
while (reader.ReadUInt32() == 0x04034b50)

// Skip the portions of the header we don't care about
reader.BaseStream.Seek(14, SeekOrigin.Current);
uint compressedSize = reader.ReadUInt32();
uint uncompressedSize = reader.ReadUInt32();
int nameLength = reader.ReadUInt16();
int extraLength = reader.ReadUInt16();
byte[] nameBytes = reader.ReadBytes(nameLength);
names.Add(Encoding.UTF8.GetString(nameBytes, 0, nameLength));
reader.BaseStream.Seek(extraLength + compressedSize, SeekOrigin.Current);

// Move the stream back to the begining
zipStream.Seek(0, SeekOrigin.Begin);
return names.ToArray();