Click here to Skip to main content
15,887,343 members
Articles / Programming Languages / F#
Tip/Trick

Reading Zip files in F#

Rate me:
Please Sign up or sign in to vote.
5.00/5 (1 vote)
9 Nov 2010CPOL 14.1K   2   1
Reading Zip files in F#
Read files from zip archive in F#. Each file is fully read as bytes.
open ICSharpCode.SharpZipLib.Zip
open System.IO 

let readAllBytes(br:Stream) = 
    let len = 2048            
    let data = Array.zeroCreate len
    use ms = new MemoryStream()
    use bw = new BinaryWriter(ms)
    let mutable is_done = false
    while(not is_done) do
        let sz = br.Read(data, 0, len) 
        is_done <- (sz <= 0)
        if (sz > 0) then
            bw.Write(data, 0, sz)
    ms.ToArray()             
    
type FileEntry = {filename: string; contents: byte[]}
type ZipEntry = File of FileEntry
                | Dir of string

let fromZip (fileName: string): seq<ZipEntry> = 
    seq{
        use s = new ZipInputStream(File.OpenRead(fileName))
        let e = ref (s.GetNextEntry())
        while (!e <> null) do
            if (!e).IsFile then
                yield File {filename = (!e).Name; 
                            contents = readAllBytes s}
            else if (!e).IsDirectory then
                yield (Dir (!e).Name)
            e := s.GetNextEntry()}

let example () = 
    //dump names of all files in zip archive
    fromZip @"test.zip"
    |> Seq.choose (function (File f) -> Some f.filename
                            | _ -> None)
    |> Seq.iter (printfn "%A")

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
United States United States
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions

 
GeneralReason for my vote of 5 very interested in F# :) thanx Pin
vdasus16-Nov-10 2:01
vdasus16-Nov-10 2:01 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.