Click here to Skip to main content
13,193,650 members (59,179 online)
Click here to Skip to main content
Add your own
alternative version

Tagged as

Stats

8.5K views
2 bookmarked
Posted 9 Nov 2010

Reading Zip files in F#

, 9 Nov 2010
Rate this:
Please Sign up or sign in to vote.
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)

Share

About the Author

Stefan Savev 2
United States United States
No Biography provided

You may also be interested in...

Pro

Comments and Discussions

 
GeneralReason for my vote of 5 very interested in F# :) thanx Pin
vdasus16-Nov-10 2:01
membervdasus16-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.

Permalink | Advertise | Privacy | Terms of Use | Mobile
Web03 | 2.8.171018.2 | Last Updated 9 Nov 2010
Article Copyright 2010 by Stefan Savev 2
Everything else Copyright © CodeProject, 1999-2017
Layout: fixed | fluid