Tuesday, March 16, 2010

Using zip

using ICSharpCode.SharpZipLib.Zip;

public class ZipFileParser
    {
        public static IEnumerable UnzipFile(Stream fileStream)
        {
            var files = new List();
            using (ZipInputStream ZipStream = new ZipInputStream(fileStream))
            {
                ZipEntry theEntry;
                while ((theEntry = ZipStream.GetNextEntry()) != null)
                {
                    if (theEntry.IsFile)
                    {
                        if (theEntry.Name != "")
                        {
                            MemoryStream stream = new MemoryStream();
                            int size = 2048;
                            byte[] data = new byte[2048];
                            while (true)
                            {
                                size = ZipStream.Read(data, 0, data.Length);
                                if (size > 0)
                                    stream.Write(data, 0, size);
                                else
                                    break;
                            }
                            stream.Seek(0, SeekOrigin.Begin);
                            files.Add(new FileStream(theEntry.Name, stream));
                        }
                    }
                }
                ZipStream.Close();
            }
            return files;
        }


        public static void ZipFiles(Stream output, IEnumerable fileStreams)
        {
            using (ZipOutputStream stream = new ZipOutputStream(output))
            {
                stream.SetLevel(6);
                foreach (var s in fileStreams)
                {
                    s.Stream.Seek(0, SeekOrigin.Begin);

                    ZipEntry entry = new ZipEntry(s.Name);
                    long bufferSize = s.Stream.Length;
                    entry.Size = bufferSize;
                    entry.DateTime = DateTime.Now;

                    var crc = new ICSharpCode.SharpZipLib.Checksums.Crc32();
                    byte[] data = new byte[bufferSize];
                    int size = s.Stream.Read(data, 0, data.Length);
                    crc.Reset();
                    crc.Update(data);
                    entry.Crc = crc.Value;
                    stream.PutNextEntry(entry);
                    stream.Write(data, 0, size);
                    s.Stream.Dispose();
                }
                stream.Finish();
            }
        }

No comments:

Post a Comment