예제 #1
2
        /// <summary>
        /// Creates a zip archive from a byte array
        /// </summary>
        /// <param name="buffer">The file in byte[] format</param>
        /// <param name="fileName">The name of the file you want to add to the archive</param>
        /// <returns></returns>
        public static byte[] CreateZipByteArray(byte[] buffer, string fileName)
        {
            ICSharpCode.SharpZipLib.Checksums.Crc32 crc = new ICSharpCode.SharpZipLib.Checksums.Crc32();

            using (System.IO.MemoryStream zipMemoryStream = new System.IO.MemoryStream())
            {
                ICSharpCode.SharpZipLib.Zip.ZipOutputStream zipOutputStream = new ICSharpCode.SharpZipLib.Zip.ZipOutputStream(zipMemoryStream);

                zipOutputStream.SetLevel(6);

                ICSharpCode.SharpZipLib.Zip.ZipEntry zipEntry = new ICSharpCode.SharpZipLib.Zip.ZipEntry(fileName);
                zipEntry.DateTime = DateTime.Now;
                zipEntry.Size = buffer.Length;

                crc.Reset();
                crc.Update(buffer);
                zipEntry.Crc = crc.Value;
                zipOutputStream.PutNextEntry(zipEntry);
                zipOutputStream.Write(buffer, 0, buffer.Length);

                zipOutputStream.Finish();

                byte[] zipByteArray = new byte[zipMemoryStream.Length];
                zipMemoryStream.Position = 0;
                zipMemoryStream.Read(zipByteArray, 0, (int)zipMemoryStream.Length);

                zipOutputStream.Close();

                return zipByteArray;
            }
        }
예제 #2
0
        /// <summary>
        /// Zips all files specified to a new zip at the destination path
        /// </summary>
        public static void ZipFiles(string destination, IEnumerable <string> files)
        {
            try
            {
                using (var zipStream = new ZipOutputStream(File.Create(destination)))
                {
                    var buffer = new byte[4096];
                    foreach (var file in files)
                    {
                        if (!File.Exists(file))
                        {
                            Log.Trace($"ZipFiles(): File does not exist: {file}");
                            continue;
                        }

                        var entry = new ZipEntry(Path.GetFileName(file));
                        zipStream.PutNextEntry(entry);
                        using (var fstream = File.OpenRead(file))
                        {
                            StreamUtils.Copy(fstream, zipStream, buffer);
                        }
                    }
                }
            }
            catch (Exception err)
            {
                Log.Error(err);
            }
        }
예제 #3
0
 /// <summary>
 /// Zips the specified <paramref name="baseFolder"/> to  the <paramref name="stream"/>.
 /// </summary>
 /// <param name="stream">Stream to write the compressed data to.</param>
 /// <param name="baseFolder">The folder to zip</param>
 /// <param name="filesToZip">
 /// the files and directories within the <paramref name="baseFolder"/> to include in the zip.
 /// These names are only matched in the <paramref name="baseFolder"/> but not recursive.
 /// You can use the default globbing (* and ?).
 /// </param>
 /// <param name="filesToIgnore">Names of the files or directories to exclude from zip. Full case sensitive match. No globbing. Directories have a trailing "/".</param>
 public static void Zip(Stream stream, string baseFolder, string[] filesToZip, string[] filesToIgnore)
 {
     using (var s = new ICSharpCode.SharpZipLib.Zip.ZipOutputStream(stream))
     {
         s.SetLevel(9);
         s.UseZip64 = ICSharpCode.SharpZipLib.Zip.UseZip64.Off;
         var baseDir = new DirectoryInfo(baseFolder);
         foreach (var fileMask in filesToZip)
         {
             foreach (var file in baseDir.GetFiles(fileMask, SearchOption.TopDirectoryOnly))
             {
                 if (IgnoreFile(baseDir.FullName, file.FullName, filesToIgnore))
                 {
                     continue;
                 }
                 var zipEntry = new ICSharpCode.SharpZipLib.Zip.ZipEntry(file.Name);
                 s.PutNextEntry(zipEntry);
                 using (var fileStream = file.OpenRead()) fileStream.CopyTo(s);
             }
             foreach (var subDir in baseDir.GetDirectories(fileMask, SearchOption.TopDirectoryOnly))
             {
                 if (IgnoreFile(baseDir.FullName, subDir.FullName, filesToIgnore))
                 {
                     continue;
                 }
                 ZipDirectory(s, baseDir, subDir, filesToIgnore);
             }
         }
         s.Finish();
     }
 }
예제 #4
0
        /// <summary>
        /// Zips the specified <paramref name="baseFolder"/> to  the <paramref name="stream"/>.
        /// </summary>
        /// <param name="stream">Stream to write the compressed data to.</param>
        /// <param name="baseFolder">The folder to zip</param>
        /// <param name="filesToZip">
        /// the files and directories within the <paramref name="baseFolder"/> to include in the zip. 
        /// These names are only matched in the <paramref name="baseFolder"/> but not recursive.
        /// You can use the default globbing (* and ?).
        /// </param>
        /// <param name="filesToIgnore">Names of the files or directories to exclude from zip. Full case sensitive match. No globbing. Directories have a trailing "/".</param>
        public static void Zip(Stream stream, string baseFolder, string[] filesToZip, string[] filesToIgnore)
        {
            using (var s = new ICSharpCode.SharpZipLib.Zip.ZipOutputStream(stream))
             {
            s.SetLevel(9);
            s.UseZip64 = ICSharpCode.SharpZipLib.Zip.UseZip64.Off;
            var baseDir = new DirectoryInfo(baseFolder);
            foreach (var fileMask in filesToZip)
            {
               foreach (var file in baseDir.GetFiles(fileMask, SearchOption.TopDirectoryOnly))
               {
                  if (IgnoreFile(baseDir.FullName, file.FullName, filesToIgnore)) continue;
                  var zipEntry = new ICSharpCode.SharpZipLib.Zip.ZipEntry(file.Name);
                  s.PutNextEntry(zipEntry);
                  using (var fileStream = file.OpenRead()) fileStream.CopyTo(s);
               }
               foreach (var subDir in baseDir.GetDirectories(fileMask, SearchOption.TopDirectoryOnly))
               {
                  if (IgnoreFile(baseDir.FullName, subDir.FullName, filesToIgnore)) continue;
                  ZipDirectory(s, baseDir, subDir, filesToIgnore);
               }

            }
            s.Finish();
             }
        }
예제 #5
0
        // *** Start programmer edit section *** (Compressor CustomMembers)
        /// <summary>
        /// Сжатие
        /// </summary>
        /// <param name="ms"></param>
        /// <returns></returns>
        public static MemoryStream Compress(MemoryStream ms)
        {
            MemoryStream restream = new MemoryStream();

            ICSharpCode.SharpZipLib.Zip.ZipOutputStream s = new ICSharpCode.SharpZipLib.Zip.ZipOutputStream(restream);

            s.SetLevel(9); // 0 - store only to 9 - means best compression

            byte[] buffer = new byte[ms.Length];

            ms.Seek(0, System.IO.SeekOrigin.Begin);

            ms.Read(buffer, 0, buffer.Length);

            ICSharpCode.SharpZipLib.Zip.ZipEntry entry = new ICSharpCode.SharpZipLib.Zip.ZipEntry("TempEntry");

            s.PutNextEntry(entry);

            s.Write(buffer, 0, buffer.Length);

            s.Finish();

            restream.Seek(0, SeekOrigin.Begin);

            return(restream);
        }
예제 #6
0
        public static void Compress(Stream data, Stream outData, string fileName)
        {
            string str = "";

            try
            {
                using (ICSharpCode.SharpZipLib.Zip.ZipOutputStream zipStream = new ICSharpCode.SharpZipLib.Zip.ZipOutputStream(outData))
                {
                    zipStream.SetLevel(3);
                    ICSharpCode.SharpZipLib.Zip.ZipEntry newEntry = new ICSharpCode.SharpZipLib.Zip.ZipEntry(fileName);
                    newEntry.DateTime = DateTime.UtcNow;
                    zipStream.PutNextEntry(newEntry);
                    data.Position = 0;
                    int    size   = (data.CanSeek) ? Math.Min((int)(data.Length - data.Position), 0x2000) : 0x2000;
                    byte[] buffer = new byte[size];
                    int    n;
                    do
                    {
                        n = data.Read(buffer, 0, buffer.Length);
                        zipStream.Write(buffer, 0, n);
                    } while (n != 0);
                    zipStream.CloseEntry();
                    zipStream.Flush();
                    zipStream.Close();
                }
            }
            catch (Exception ex)
            {
                str = ex.Message;
            }
        }
예제 #7
0
        public static MemoryStream CreateToMemoryStream(MemoryStream memStreamIn, string zipEntryName)
        {
            MemoryStream outputMemStream = new MemoryStream();
            var          zipStream       = new ICSharpCode.SharpZipLib.Zip.ZipOutputStream(outputMemStream);

            zipStream.SetLevel(3); //0-9, 9 being the highest level of compression

            var newEntry = new ICSharpCode.SharpZipLib.Zip.ZipEntry(zipEntryName);

            newEntry.DateTime = DateTime.Now;

            zipStream.PutNextEntry(newEntry);

            ICSharpCode.SharpZipLib.Core.StreamUtils.Copy(memStreamIn, zipStream, new byte[4096]);
            zipStream.CloseEntry();

            zipStream.IsStreamOwner = false; // False stops the Close also Closing the underlying stream.
            zipStream.Close();               // Must finish the ZipOutputStream before using outputMemStream.

            outputMemStream.Position = 0;
            return(outputMemStream);

            // Alternative outputs:
            // ToArray is the cleaner and easiest to use correctly with the penalty of duplicating allocated memory.

            //byte[] byteArrayOut = outputMemStream.ToArray();

            // GetBuffer returns a raw buffer raw and so you need to account for the true length yourself.
            //byte[] byteArrayOut = outputMemStream.GetBuffer();
            //long len = outputMemStream.Length;
        }
예제 #8
0
        /// <summary>
        /// Zip và tải xuống file nén các file
        /// </summary>
        /// <param name="serial"></param>
        /// <param name="listFiles"></param>
        /// <param name="path"></param>
        /// <param name="response"></param>
        public void DownloadMultiFiles(string serial, List <string> listFiles, string path, HttpResponse response)
        {
            string fullName    = "";
            string zipName     = serial + ".zip";
            string zipFullPath = path + zipName;

            ICSharpCode.SharpZipLib.Zip.ZipOutputStream zipOut =
                new ICSharpCode.SharpZipLib.Zip.ZipOutputStream(System.IO.File.Create(zipFullPath));
            foreach (string fileName in listFiles)
            {
                fullName = path + "\\" + fileName;
                System.IO.FileInfo fi = new System.IO.FileInfo(fullName);
                ICSharpCode.SharpZipLib.Zip.ZipEntry entry = new ICSharpCode.SharpZipLib.Zip.ZipEntry(fi.Name);
                System.IO.FileStream sReader = System.IO.File.OpenRead(fullName);
                byte[] buff = new byte[Convert.ToInt32(sReader.Length)];
                sReader.Read(buff, 0, (int)sReader.Length);
                entry.DateTime = fi.LastWriteTime;
                entry.Size     = sReader.Length;
                sReader.Close();
                zipOut.PutNextEntry(entry);
                zipOut.Write(buff, 0, buff.Length);
            }
            zipOut.Finish();
            zipOut.Close();
            DownloadSingleFile(zipName, zipFullPath, response);
        }
예제 #9
0
        /// <summary>
        /// Compresses the specified source file.
        /// </summary>
        /// <param name="source">The source file to be compressed</param>
        /// <param name="destination">The destination zip file path</param>
        /// <param name="zipEntryName">The zip entry name for the file</param>
        /// <param name="deleteOriginal">True to delete the source file upon completion</param>
        public static void Zip(string source, string destination, string zipEntryName, bool deleteOriginal)
        {
            try
            {
                var buffer = new byte[4096];
                using (var stream = new ZipOutputStream(File.Create(destination)))
                {
                    //Zip the text file.
                    var entry = new ZipEntry(zipEntryName);
                    stream.PutNextEntry(entry);

                    using (var fs = File.OpenRead(source))
                    {
                        int sourceBytes;
                        do
                        {
                            sourceBytes = fs.Read(buffer, 0, buffer.Length);
                            stream.Write(buffer, 0, sourceBytes);
                        }while (sourceBytes > 0);
                    }
                }

                //Delete the old text file:
                if (deleteOriginal)
                {
                    File.Delete(source);
                }
            }
            catch (Exception err)
            {
                Log.Error(err);
            }
        }
예제 #10
0
        /// <summary>
        /// Create a zip file of the supplied file names and string data source
        /// </summary>
        /// <param name="zipPath">Output location to save the file.</param>
        /// <param name="filenamesAndData">File names and data in a dictionary format.</param>
        /// <returns>True on successfully creating the zip file.</returns>
        public static bool ZipData(string zipPath, Dictionary<string, string> filenamesAndData)
        {
            try
            {
                //Create our output
                using (var stream = new ZipOutputStream(File.Create(zipPath)))
                {
                    stream.SetLevel(0);
                    foreach (var filename in filenamesAndData.Keys)
                    {
                        //Create the space in the zip file:
                        var entry = new ZipEntry(filename);
                        var data = filenamesAndData[filename];
                        var bytes = Encoding.Default.GetBytes(data);
                        stream.PutNextEntry(entry);
                        stream.Write(bytes, 0, bytes.Length);
                        stream.CloseEntry();
                    } // End For Each File.

                    //Close stream:
                    stream.Finish();
                    stream.Close();
                } // End Using
            }
            catch (Exception err)
            {
                Log.Error(err);
                return false;
            }
            return true;
        }
예제 #11
0
        void lv3_DoubleClick(object sender, EventArgs e)
        {
            ListViewItem lvi = lv3.SelectedItems[0];
            ArrayList    al  = (ArrayList)lvi.Tag;
            FileInfo     fi  = (FileInfo)al[0];

            zip.Zip.ZipFile  zf = (zip.Zip.ZipFile)al[1];
            zip.Zip.ZipEntry ze = (zip.Zip.ZipEntry)al[2];

            string strFName = fi.FullName;

            string strName   = ze.Name;
            string strParent = "";

            if (strName.IndexOf("/") != -1)
            {
                string[] strNameArr = strName.Split(Encoding.Default.GetChars(Encoding.Default.GetBytes("/")));
                strName = strNameArr[strNameArr.Length - 1];
                for (int i = 0; i < strNameArr.Length - 2; i++)
                {
                    strParent += "\\" + strNameArr[i];
                }
            }

            if (isZip(strFName))
            {
                zip.Zip.FastZip fz = new ICSharpCode.SharpZipLib.Zip.FastZip();
                fz.ExtractZip(strFName, Application.UserAppDataPath + strParent, ze.Name);

                FileInfo[] fins = new FileInfo[1];
                fins.SetValue(new FileInfo(Application.UserAppDataPath + "\\" + ze.Name), 0);
                PropForm pf = new PropForm(fins);
                pf.Show();
            }
        }
예제 #12
0
        /// <summary>
        /// Create a zip file of the supplied file names and string data source
        /// </summary>
        /// <param name="zipPath">Output location to save the file.</param>
        /// <param name="filenamesAndData">File names and data in a dictionary format.</param>
        /// <returns>True on successfully creating the zip file.</returns>
        public static bool ZipData(string zipPath, Dictionary <string, string> filenamesAndData)
        {
            try
            {
                //Create our output
                using (var stream = new ZipOutputStream(File.Create(zipPath)))
                {
                    foreach (var filename in filenamesAndData.Keys)
                    {
                        //Create the space in the zip file:
                        var entry = new ZipEntry(filename);
                        var data  = filenamesAndData[filename];
                        var bytes = Encoding.Default.GetBytes(data);
                        stream.PutNextEntry(entry);
                        stream.Write(bytes, 0, bytes.Length);
                        stream.CloseEntry();
                    } // End For Each File.

                    //Close stream:
                    stream.Finish();
                    stream.Close();
                } // End Using
            }
            catch (Exception err)
            {
                Log.Error(err);
                return(false);
            }
            return(true);
        }
예제 #13
0
 public static void WriteFileToZip(ICSharpCode.SharpZipLib.Zip.ZipOutputStream stream, string filename, byte[] bytes)
 {
     ICSharpCode.SharpZipLib.Zip.ZipEntry ze = new ICSharpCode.SharpZipLib.Zip.ZipEntry(filename);
     ze.Size = bytes.Length;
     stream.PutNextEntry(ze);
     stream.Write(bytes, 0, bytes.Length);
 }
예제 #14
0
 private void listPackageFiles_SelectedIndexChanged(object sender, System.EventArgs e)
 {
     if (zipFile != null)
     {                   // the zip file exists
         ICSCZL.Zip.ZipEntry theEntry = (ICSCZL.Zip.ZipEntry) this.listPackageFiles.SelectedItem;
         txtPackageDetails.Text = "";
         int              size   = 2048;
         byte[]           toDisp = new byte[2048];
         System.IO.Stream s      = zipFile.GetInputStream(theEntry);
         txtPackageDetails.Visible = false;
         string building = "";
         progressReading.Value   = 0;
         progressReading.Maximum = (int)System.Math.Round(((float)theEntry.Size / 2048.0f) + 1.0f);
         while (true)
         {
             size = s.Read(toDisp, 0, toDisp.Length);
             if (size > 0)
             {
                 building = "";
                 for (int i = 0; i < size; ++i)
                 {
                     building += (char)toDisp[i];
                 }
                 txtPackageDetails.Text += building;
                 progressReading.Value++;
             }
             else
             {
                 break;
             }
         }
         progressReading.Value     = progressReading.Maximum;
         txtPackageDetails.Visible = true;
     }
 }
예제 #15
0
        public void ZIP(string SourcePath, string DestFile, int Compression, bool Subdir)
        {
            string[] fileList = GetFileList(SourcePath, Subdir);

            if (!Directory.Exists(Path.GetDirectoryName(DestFile)))
            {
                Directory.CreateDirectory(Path.GetDirectoryName(DestFile));
            }
            FileStream fs = File.Create(DestFile);

            ICSharpCode.SharpZipLib.Zip.ZipOutputStream s = new ICSharpCode.SharpZipLib.Zip.ZipOutputStream(fs);
            s.SetLevel(Compression);
            foreach (string fileName in fileList)
            {
                FileStream fs2 = File.OpenRead(fileName);

                byte[] buffer = new byte[fs2.Length];
                fs2.Read(buffer, 0, buffer.Length);
                fs2.Close();

                ICSharpCode.SharpZipLib.Zip.ZipEntry entry = new ICSharpCode.SharpZipLib.Zip.ZipEntry(fileName);

                s.PutNextEntry(entry);

                s.Write(buffer, 0, buffer.Length);
            }
            s.Finish();
            s.Close();
        }
        /// <summary>
        /// Exports the query results to an excel file per query.
        /// </summary>
        /// <param name="viewType">Indicates the type of response view.</param>
        /// <returns></returns>
        public Stream ExportAsExcel(TaskItemTypes viewType)
        {
            MemoryStream ms = new MemoryStream();
            var          includeDataMartName = viewType != TaskItemTypes.AggregateResponse;

            if (Queries.Count() > 1)
            {
                var zipStream = new ICSharpCode.SharpZipLib.Zip.ZipOutputStream(ms);
                zipStream.IsStreamOwner = false;

                foreach (var grouping in Queries)
                {
                    var    datamartAcronym  = includeDataMartName ? "-" + grouping.Select(g => g.DataMartAcronym).FirstOrDefault() : string.Empty;
                    string zipEntryFilename = Path.ChangeExtension(CleanFilename(grouping.Key.QueryName + datamartAcronym), "xlsx");

                    var zipEntry = new ICSharpCode.SharpZipLib.Zip.ZipEntry(zipEntryFilename);
                    zipEntry.DateTime = DateTime.Now;
                    zipStream.PutNextEntry(zipEntry);

                    WriteExcel(zipStream, grouping.AsEnumerable(), includeDataMartName);
                    zipStream.CloseEntry();
                }

                zipStream.Close();
            }
            else
            {
                WriteExcel(ms, Queries.ElementAt(0).ToArray(), includeDataMartName);
            }

            ms.Position = 0;

            return(ms);
        }
예제 #17
0
        private Hashtable searchInCompressed(FileInfo fi, string in_searchstring)
        {
            Hashtable ht_ret = new Hashtable();

            if (fi.Extension.ToLower().Equals(".zip"))
            {
                zip.Zip.ZipFile zf     = new ICSharpCode.SharpZipLib.Zip.ZipFile(fi.FullName);
                IEnumerator     ienumk = zf.GetEnumerator();
                ienumk.MoveNext();

                do
                {
                    GC.Collect();
                    Application.DoEvents();

                    try
                    {
                        zip.Zip.ZipEntry ze = (zip.Zip.ZipEntry)ienumk.Current;
                        if (ze.Name.ToLower().IndexOf(in_searchstring) != -1)
                        {
                            ht_ret.Add(ht_ret.Count, ze);
                        }
                    }
                    catch (Exception ex)
                    {
                    }
                } while (ienumk.MoveNext());
            }
            return(ht_ret);
        }
예제 #18
0
        /// <summary>
        /// Zips the specified <paramref name="baseFolder"/>.
        /// </summary>
        /// <param name="baseFolder">The folder to zip</param>
        /// <param name="filesToZip">
        /// the files and directories within the <paramref name="baseFolder"/> to include in the zip.
        /// These names are only matched in the <paramref name="baseFolder"/> but not recursive.
        /// You can use the default globbing (* and ?).
        /// </param>
        /// <param name="filesToIgnore">Names of the files or directories to exclude from zip. Full case sensitive match. No globbing. Directories have a trailing "/".</param>
        public void Zip(string baseFolder, string[] filesToZip, string[] filesToIgnore)
        {
            var baseDir = new DirectoryInfo(baseFolder);

            foreach (var fileMask in filesToZip)
            {
                foreach (var file in baseDir.GetFiles(fileMask, SearchOption.TopDirectoryOnly))
                {
                    if (IgnoreFile(baseDir.FullName, file.FullName, filesToIgnore))
                    {
                        continue;
                    }
                    var zipEntry = new ICSharpCode.SharpZipLib.Zip.ZipEntry(file.Name);
                    zipStream.PutNextEntry(zipEntry);
                    using (var fileStream = file.OpenRead()) fileStream.CopyTo(zipStream);
                }
                foreach (var subDir in baseDir.GetDirectories(fileMask, SearchOption.TopDirectoryOnly))
                {
                    if (IgnoreFile(baseDir.FullName, subDir.FullName, filesToIgnore))
                    {
                        continue;
                    }
                    ZipDirectory(zipStream, baseDir, subDir, filesToIgnore);
                }
            }
        }
예제 #19
0
        /// <summary>
        /// Constrói um pacote com as dependencias informadas.
        /// </summary>
        /// <param name="outStream">Stream de saída.</param>
        /// <param name="entries"></param>
        /// <returns></returns>
        public static void BuildPackage(System.IO.Stream outStream, IEnumerator <Tuple <DataEntryVersion, System.IO.Stream> > entries)
        {
            outStream.Require("outStream").NotNull();
            outStream.Require("entries").NotNull();
            var buffer = new byte[1024];
            int read   = 0;
            var zipOut = new ICSharpCode.SharpZipLib.Zip.ZipOutputStream(outStream);

            while (entries.MoveNext())
            {
                var item = entries.Current;
                if (item == null)
                {
                    continue;
                }
                var entryName = item.Item1.TypeName.FullName;
                var entry     = new ICSharpCode.SharpZipLib.Zip.ZipEntry(entryName);
                entry.Size = item.Item2.Length;
                zipOut.PutNextEntry(entry);
                while ((read = item.Item2.Read(buffer, 0, buffer.Length)) > 0)
                {
                    zipOut.Write(buffer, 0, read);
                }
                zipOut.CloseEntry();
            }
            zipOut.Finish();
            zipOut.Flush();
        }
예제 #20
0
        private System.Xml.XmlDocument GetContentXmlFile(ICSharpCode.SharpZipLib.Zip.ZipFile zipFile)
        {
            // Get file(in zip archive) that contains data ("content.xml").
            // ICSharpCode.SharpZipLib.Zip.ZipEntry contentZipEntry = zipFile["content.xml"];

            // Extract that file to MemoryStream.
            // Stream contentStream = new MemoryStream();
            // contentZipEntry.Extract(contentStream);
            // contentStream.Seek(0, SeekOrigin.Begin);

            // Create XmlDocument from MemoryStream (MemoryStream contains content.xml).
            System.Xml.XmlDocument contentXml = new System.Xml.XmlDocument();


            ICSharpCode.SharpZipLib.Zip.ZipEntry ze = zipFile.GetEntry("content.xml");
            if (ze == null)
            {
                throw new System.ArgumentException("content.xml not found in Zip");
            } // End if (ze == null)

            using (System.IO.Stream contentStream = zipFile.GetInputStream(ze))
            {
                // do something with ZipInputStream
                contentXml.Load(contentStream);
            } // End Using contentStream

            return(contentXml);
        } // End Function GetContentXmlFile
예제 #21
0
        public static byte[] Zip(this byte[] data, int level = 9)
        {
            if (data == null)
            {
                return(null);
            }
            if (data.Length == 0)
            {
                return(new byte[0]);
            }

            level = level.ToClosedInterval(0, 9);

            using (MemoryStream memory = new MemoryStream())
            {
                using (ICSharpCode.SharpZipLib.Zip.ZipOutputStream stream = new ICSharpCode.SharpZipLib.Zip.ZipOutputStream(memory))
                {
                    stream.SetLevel(level);
                    ICSharpCode.SharpZipLib.Zip.ZipEntry Entry = new ICSharpCode.SharpZipLib.Zip.ZipEntry("");

                    Entry.Size = data.Length;
                    stream.PutNextEntry(Entry);
                    stream.Write(data, 0, data.Length);
                }

                return(memory.ToArray());
            }
        }
예제 #22
0
 public Entry(ICSharpCode.SharpZipLib.Zip.ZipEntry zipEntry)
 {
     Name          = System.IO.Path.GetFileName(zipEntry.Name.TrimEnd('/'));
     Kind          = zipEntry.IsDirectory ? EntryKind.ZipDirectoryEntry : EntryKind.ZipFileEntry;
     LastWriteTime = zipEntry.DateTime;
     Node          = null;
     Size          = zipEntry.IsFile ? zipEntry.Size : 0;
 }
예제 #23
0
        /// <summary>
        /// 压缩
        /// </summary>
        /// <param name="zipStream">压缩流</param>
        /// <param name="filePath">文件或文件夹路径</param>
        /// <param name="rootDirPath">根路径(就是压缩后的文件存储的路径)</param>
        private static void appendStream(ICSharpCode.SharpZipLib.Zip.ZipOutputStream zipStream, string filePath, string fileName, string rootDirPath)
        {
            if (string.IsNullOrEmpty(filePath))
            {
                return;
            }
            filePath = filePath.Replace('/', '\\');
            if (string.IsNullOrEmpty(filePath.Replace(rootDirPath, "").Trim('\\')))
            {
                return;
            }
            if (Directory.Exists(filePath))//若为文件夹
            {
                DirectoryInfo    dir            = new DirectoryInfo(filePath);
                FileSystemInfo[] fileSystemList = dir.GetFileSystemInfos();
                if (fileSystemList == null || fileSystemList.Length < 1)                                                                                           //若该文件加下面没有子文件或文件夹,需创建空的文件夹
                {
                    ICSharpCode.SharpZipLib.Zip.ZipEntry zipEntry = new ICSharpCode.SharpZipLib.Zip.ZipEntry(filePath.Replace(rootDirPath, "").Trim('\\') + "\\"); //末尾“\\”用于文件夹的标记
                    zipStream.PutNextEntry(zipEntry);
                    return;
                }
                foreach (FileSystemInfo fileSystem in fileSystemList)
                {
                    appendStream(zipStream, fileSystem.FullName, rootDirPath);
                }
            }
            else if (System.IO.File.Exists(filePath))
            {
                FileStream   fs = System.IO.File.OpenRead(filePath);
                BinaryReader br = new BinaryReader(fs);
                try
                {
                    FileInfo file = new FileInfo(filePath);//根据文件路径获取文件名的简便方法
                    ICSharpCode.SharpZipLib.Zip.ZipEntry zipEntry = string.IsNullOrEmpty(fileName) ?
                                                                    new ICSharpCode.SharpZipLib.Zip.ZipEntry(filePath.Replace(rootDirPath, "").Trim('\\')) :
                                                                    new ICSharpCode.SharpZipLib.Zip.ZipEntry(fileName);

                    zipStream.PutNextEntry(zipEntry); //为压缩文件流提供一个容器
                    int packSize = 10240;
                    int maxCount = (int)Math.Ceiling((fs.Length + 0.0) / packSize);
                    for (int i = 0; i < maxCount; i++)
                    {
                        byte[] b = br.ReadBytes(packSize); //将文件流加入缓冲字节中
                        zipStream.Write(b, 0, b.Length);   //写入字节
                    }
                }
                catch (Exception ex)
                {
                    throw ex;
                }
                finally
                {
                    br.Close();
                    fs.Close();
                    fs.Dispose();
                }
            }
        }
예제 #24
0
        /// <summary>
        /// Zips the specified <paramref name="baseFolder"/>.
        /// </summary>
        /// <param name="fileName">Relative filename in zip.</param>
        /// <param name="contentStream">The content of the file</param>
        public void Zip(string fileName, Stream contentStream)
        {
            var nameTransform = new ICSharpCode.SharpZipLib.Zip.ZipNameTransform();
            var relativeName  = nameTransform.TransformFile(fileName);
            var zipEntry      = new ICSharpCode.SharpZipLib.Zip.ZipEntry(relativeName);

            zipStream.PutNextEntry(zipEntry);
            contentStream.CopyTo(zipStream);
        }
        public static void CheckZipEntry(this ICSharpCode.SharpZipLib.Zip.ZipEntry input)
        {
            var fullName = input.Name.Replace('\\', '/');

            if (fullName.StartsWith("..") || fullName.Contains("/../"))
            {
                throw new Exception("Illegal Zip File");
            }
        }
예제 #26
0
 public ZipFile(
     ICSharpCode.SharpZipLib.Zip.ZipEntry zipArchiveEntry,
     ICSharpCode.SharpZipLib.Zip.ZipFile zipArchive,
     string path, string zipPath,
     ZipOption zipOption = null) : base(path, "zip")
 {
     _zipArchiveEntry = zipArchiveEntry;
     _zipArchive      = zipArchive;
     _zipOption       = zipOption ?? new ZipOption();
     ZipPath          = zipPath;
 }
예제 #27
0
 /// <summary>
 /// Performs an in memory zip of the specified bytes
 /// </summary>
 /// <param name="bytes">The file contents in bytes to be zipped</param>
 /// <param name="zipEntryName">The zip entry name</param>
 /// <returns>The zipped file as a byte array</returns>
 public static byte[] ZipBytes(byte[] bytes, string zipEntryName)
 {
     using (var memoryStream = new MemoryStream())
         using (var stream = new ZipOutputStream(memoryStream))
         {
             var entry = new ZipEntry(zipEntryName);
             stream.PutNextEntry(entry);
             var buffer = new byte[16 * 1024];
             StreamUtils.Copy(new MemoryStream(bytes), stream, buffer);
             return(memoryStream.GetBuffer());
         }
 }
예제 #28
0
        public string[] GetFiles()
        {
            List <string> list = new List <string>();

            for (int i = 0; i < Convert.ToInt32(zip.Count); i++)
            {
                ICSharpCode.SharpZipLib.Zip.ZipEntry entry = zip[i];
                string fileName = entry.Name;
                list.Add(fileName);
            }
            return(list.ToArray());
        }
        /// <summary>
        /// Exports the responses in csv format, if the response is multi-query each query response will be a separate csv file zipped into a file of the request name.
        /// </summary>
        /// <param name="viewType">The response result view type, Individual or Aggregate.</param>
        /// <returns></returns>
        public Stream ExportAsCSV(TaskItemTypes viewType)
        {
            var queries             = Queries.ToArray();
            var includeDataMartName = viewType != TaskItemTypes.AggregateResponse;

            MemoryStream ms = new MemoryStream();

            if (queries.Count() > 1)
            {
                var zipStream = new ICSharpCode.SharpZipLib.Zip.ZipOutputStream(ms);
                zipStream.IsStreamOwner = false;

                foreach (var grouping in Queries)
                {
                    var    datamartAcronym  = includeDataMartName ? "-" + grouping.Select(g => g.DataMartAcronym).FirstOrDefault() : string.Empty;
                    string zipEntryFilename = Path.ChangeExtension(CleanFilename(grouping.Key.QueryName + datamartAcronym), "csv");

                    var zipEntry = new ICSharpCode.SharpZipLib.Zip.ZipEntry(zipEntryFilename);
                    zipEntry.DateTime = DateTime.Now;
                    zipStream.PutNextEntry(zipEntry);

                    using (var writer = new StreamWriter(zipStream, System.Text.Encoding.Default, 1024, true))
                    {
                        for (int i = 0; i < grouping.Count(); i++)
                        {
                            var responseResult = grouping.ElementAt(i);
                            WriteCSV(writer, responseResult, i == 0, includeDataMartName);
                        }

                        writer.Flush();
                        zipStream.CloseEntry();
                    }
                }

                zipStream.Close();
            }
            else
            {
                var firstQueryGrouping = Queries.ElementAt(0).ToArray();
                using (var writer = new StreamWriter(ms, System.Text.Encoding.Default, 1024, true))
                {
                    for (int i = 0; i < firstQueryGrouping.Length; i++)
                    {
                        WriteCSV(writer, firstQueryGrouping[i], i == 0, includeDataMartName);
                    }
                    writer.Flush();
                }
            }

            ms.Position = 0;
            return(ms);
        }
예제 #30
0
        /// <summary>
        /// Zips the specified <paramref name="baseFolder"/>.
        /// </summary>
        /// <param name="fileName">Relative filename in zip.</param>
        /// <param name="content">The content of the file</param>
        public void Zip(string fileName, byte[] content)
        {
            if (content == null)
            {
                return;
            }
            var nameTransform = new ICSharpCode.SharpZipLib.Zip.ZipNameTransform();
            var relativeName  = nameTransform.TransformFile(fileName);
            var zipEntry      = new ICSharpCode.SharpZipLib.Zip.ZipEntry(relativeName);

            zipStream.PutNextEntry(zipEntry);
            zipStream.Write(content, 0, content.Length);
        }
예제 #31
0
 bool FindEntry(string entryname, out SharpZipLib.Zip.ZipEntry entry)
 {
     try
     {
         entry = zip.GetEntry(entryname);
         return(entry != null);
     }
     catch (Exception e)
     {
         LogUtil.LogError(e.Message);
         entry = null;
         return(false);
     }
 }
예제 #32
0
        public static MemoryStream CompressStream(MemoryStream stream, string entryname)
        {
            MemoryStream ms = new MemoryStream();

            using (ICSharpCode.SharpZipLib.Zip.ZipOutputStream zipstream = new ICSharpCode.SharpZipLib.Zip.ZipOutputStream(ms))
            {
                ICSharpCode.SharpZipLib.Zip.ZipEntry entry = new ICSharpCode.SharpZipLib.Zip.ZipEntry(entryname);
                entry.DateTime = DateTime.Now;
                zipstream.PutNextEntry(entry);
                zipstream.Write(stream.ToArray(), 0, (int)stream.Length);
                zipstream.Flush();
                zipstream.Finish();
                zipstream.Close();
            }
            return(ms);
        }
예제 #33
0
        public static void ZipFile(System.Collections.Generic.List <string> filesToZip, string outFile, int compression = 3, bool IsMapPath = true)
        {
            outFile = IsMapPath ? TM.Core.IO.MapPath(outFile) : outFile;
            if (compression < 0 || compression > 9)
            {
                throw new ArgumentException("Invalid compression rate (just 0-9).");
            }

            if (!Directory.Exists(new FileInfo(outFile).Directory.ToString()))
            {
                throw new ArgumentException("The Path does not exist.");
            }

            foreach (string c in filesToZip)
            {
                if (!File.Exists(IsMapPath ? TM.Core.IO.MapPath(c) : c))
                {
                    throw new ArgumentException(string.Format("The File {0} does not exist!", c));
                }
            }

            var crc32  = new ICSharpCode.SharpZipLib.Checksum.Crc32();
            var stream = new ICSharpCode.SharpZipLib.Zip.ZipOutputStream(File.Create(outFile));

            stream.SetLevel(compression);

            for (int i = 0; i < filesToZip.Count; i++)
            {
                var entry = new ICSharpCode.SharpZipLib.Zip.ZipEntry(Path.GetFileName(filesToZip[i]));
                entry.DateTime = DateTime.Now;
                var _filesToZip = IsMapPath ? TM.Core.IO.MapPath(filesToZip[i]) : filesToZip[i];
                using (FileStream fs = File.OpenRead(_filesToZip))
                {
                    byte[] buffer = new byte[fs.Length];
                    fs.Read(buffer, 0, buffer.Length);
                    entry.Size = fs.Length;
                    fs.Close();
                    crc32.Reset();
                    crc32.Update(buffer);
                    entry.Crc = crc32.Value;
                    stream.PutNextEntry(entry);
                    stream.Write(buffer, 0, buffer.Length);
                }
            }
            stream.Finish();
            stream.Close();
        }
예제 #34
0
        /// <summary>
        /// Create a zip file of the supplied file names and string data source
        /// </summary>
        /// <param name="zipPath">Output location to save the file.</param>
        /// <param name="filenamesAndData">File names and data in a dictionary format.</param>
        /// <returns>True on successfully creating the zip file.</returns>
        public static bool ZipData(string zipPath, Dictionary<string, string> filenamesAndData)
        {
            var success = true;
            var buffer = new byte[4096];

            try
            {
                //Create our output
                using (var stream = new ZipOutputStream(File.Create(zipPath)))
                {
                    foreach (var filename in filenamesAndData.Keys)
                    {
                        //Create the space in the zip file:
                        var entry = new ZipEntry(filename);
                        //Get a Byte[] of the file data:
                        var file = Encoding.Default.GetBytes(filenamesAndData[filename]);
                        stream.PutNextEntry(entry);

                        using (var ms = new MemoryStream(file))
                        {
                            int sourceBytes;
                            do
                            {
                                sourceBytes = ms.Read(buffer, 0, buffer.Length);
                                stream.Write(buffer, 0, sourceBytes);
                            }
                            while (sourceBytes > 0);
                        }
                    } // End For Each File.

                    //Close stream:
                    stream.Finish();
                    stream.Close();
                } // End Using
            }
            catch (Exception err)
            {
                Log.Error(err);
                success = false;
            }
            return success;
        }
예제 #35
0
 public static void Zip(string data, string zipPath, string zipEntry)
 {
     using (var stream = new ZipOutputStream(File.Create(zipPath)))
     {
         var entry = new ZipEntry(zipEntry);
         stream.PutNextEntry(entry);
         var buffer = new byte[4096];
         using (var dataReader = new MemoryStream(Encoding.Default.GetBytes(data)))
         {
             int sourceBytes;
             do
             {
                 sourceBytes = dataReader.Read(buffer, 0, buffer.Length);
                 stream.Write(buffer, 0, sourceBytes);
             }
             while (sourceBytes > 0);
         }
     }
 }
예제 #36
0
        /// <summary>
        /// Compress a given file and delete the original file. Automatically rename the file to name.zip.
        /// </summary>
        /// <param name="textPath">Path of the original file</param>
        /// <param name="deleteOriginal">Boolean flag to delete the original file after completion</param>
        /// <returns>String path for the new zip file</returns>
        public static string Zip(string textPath, bool deleteOriginal = true)
        {
            var zipPath = "";

            try
            {
                var buffer = new byte[4096];
                zipPath = textPath.Replace(".csv", ".zip");
                zipPath = zipPath.Replace(".txt", ".zip");
                //Open the zip:
                using (var stream = new ZipOutputStream(File.Create(zipPath)))
                {
                    //Zip the text file.
                    var entry = new ZipEntry(Path.GetFileName(textPath));
                    stream.PutNextEntry(entry);

                    using (var fs = File.OpenRead(textPath))
                    {
                        int sourceBytes;
                        do
                        {
                            sourceBytes = fs.Read(buffer, 0, buffer.Length);
                            stream.Write(buffer, 0, sourceBytes);
                        }
                        while (sourceBytes > 0);
                    }
                    //Close stream:
                    stream.Finish();
                    stream.Close();
                }
                //Delete the old text file:
                if (deleteOriginal) File.Delete(textPath);
            }
            catch (Exception err)
            {
                Log.Error("QC.Data.Zip(): " + err.Message);
            }
            return zipPath;
        }
예제 #37
0
 /// <summary>
 /// Zips the specified <paramref name="baseFolder"/>.
 /// </summary>
 /// <param name="fileName">Relative filename in zip.</param>
 /// <param name="content">The content of the file</param>
 public void Zip(string fileName, byte[] content)
 {
     if (content==null) return;
      var nameTransform = new ICSharpCode.SharpZipLib.Zip.ZipNameTransform();
      var relativeName = nameTransform.TransformFile(fileName);
      var zipEntry = new ICSharpCode.SharpZipLib.Zip.ZipEntry(relativeName);
      zipStream.PutNextEntry(zipEntry);
      zipStream.Write(content, 0, content.Length);
 }
예제 #38
0
 private void menuExportTeamData_Click(object sender, EventArgs e)
 {
     SaveFileDialog d = new SaveFileDialog();
     d.AddExtension = true;
     d.DefaultExt = ".zip";
     d.Filter = T("Tutti i file ZIP (*.zip)")+"|*.zip";
     d.FileName = "RMO-Team-Data-" + DateTime.Now.ToString("yyyy-MM-dd") + ".zip";
     d.InitialDirectory = My.Dir.Desktop;
     d.OverwritePrompt = true;
     d.Title = T("Nome del file da esportare");
     if (d.ShowDialog() == DialogResult.OK)
     {
         try
         {
             string[] filenames = System.IO.Directory.GetFiles(PATH_HISTORY, "*.team");
             progressBar.Value = 0;
             progressBar.Maximum = filenames.Length;
             using (ICSharpCode.SharpZipLib.Zip.ZipOutputStream s = new ICSharpCode.SharpZipLib.Zip.ZipOutputStream(System.IO.File.Create(d.FileName)))
             {
                 s.SetLevel(9);
                 byte[] buffer = new byte[4096];
                 foreach (string file in filenames)
                 {
                     ICSharpCode.SharpZipLib.Zip.ZipEntry entry = new ICSharpCode.SharpZipLib.Zip.ZipEntry(System.IO.Path.GetFileName(file));
                     entry.DateTime = DateTime.Now;
                     s.PutNextEntry(entry);
                     using (System.IO.FileStream fs = System.IO.File.OpenRead(file))
                     {
                         int sourceBytes;
                         do
                         {
                             sourceBytes = fs.Read(buffer, 0, buffer.Length);
                             s.Write(buffer, 0, sourceBytes);
                         }
                         while (sourceBytes > 0);
                     }
                     progressBar.Value++;
                 }
                 s.Finish();
                 s.Close();
                 lStatus.Text = T("Esportazione del backup ultimata correttamente!");
             }
         }
         catch (Exception ex) { My.Box.Errore(T("Errore durante l'esportazione del backup")+"\r\n"+ex.Message); }
         progressBar.Value = 0;
     }
 }
예제 #39
0
        /// <summary>
        /// Zips all files specified to a new zip at the destination path
        /// </summary>
        public static void ZipFiles(string destination, IEnumerable<string> files)
        {
            try
            {
                using (var zipStream = new ZipOutputStream(File.Create(destination)))
                {
                    var buffer = new byte[4096];
                    foreach (var file in files)
                    {
                        if (!File.Exists(file))
                        {
                            Log.Trace("ZipFiles(): File does not exist: " + file);
                            continue;
                        }

                        var entry = new ZipEntry(Path.GetFileName(file));
                        zipStream.PutNextEntry(entry);
                        using (var fstream = File.OpenRead(file))
                        {
                            StreamUtils.Copy(fstream, zipStream, buffer);
                        }
                    }
                }
            }
            catch (Exception err)
            {
                Log.Error(err);
            }
        }
예제 #40
0
 /// <summary>
 /// Creates a new wrapper around a zip file entry.
 /// </summary>
 /// <param name="baseEntry"></param>
 public ZipEntry(ICSharpCode.SharpZipLib.Zip.ZipEntry baseEntry)
 {
     this.baseEntry = baseEntry;
 }
 protected virtual void SerializeHeightmap(Map map, Stream stream)
 {
     // Heightmap serialization method 3
     var i = new ICSharpCode.SharpZipLib.Zip.ZipOutputStream(stream);
     var entry = new ICSharpCode.SharpZipLib.Zip.ZipEntry("Heightmap");
     i.PutNextEntry(entry);
     var bw = new BinaryWriter(i);
     bw.Write(map.Ground.Heightmap.GetLength(0));
     bw.Write(map.Ground.Heightmap.GetLength(1));
     for (var y = 0; y < map.Ground.Heightmap.GetLength(0); y++)
         for (var x = 0; x < map.Ground.Heightmap.GetLength(1); x++)
             bw.Write(map.Ground.Heightmap[y, x].R);
     i.Close();
 }
예제 #42
0
 /// <summary>
 /// Appends a file entry to the archive.
 /// </summary>
 /// <param name="filename"></param>
 /// <param name="size"></param>
 /// <returns></returns>
 public IArchiveEntry CreateFileEntry(string filename, long size)
 {
     var e = new ICSharpCode.SharpZipLib.Zip.ZipEntry(filename);
     return new ZipEntry(e);
 }
예제 #43
0
        /// <summary>
        /// Creates a file in the archive and returns a writeable stream
        /// </summary>
        /// <param name="file">The name of the file to create</param>
        /// <param name="lastWrite">The time the file was last written</param>
        /// <returns>A writeable stream for the file contents</returns>
        public System.IO.Stream CreateFile(string file, DateTime lastWrite)
        {
            #if !SHARPZIPLIBWORKS
            if (m_stream == null)
                throw new Exception(Strings.FileArchiveZip.AttemptWriteWhileReadingError);
            #endif
            string entryname = PathFromFilesystem(file);
            m_headersize += 46 + 24 + _filenameEncoding.GetByteCount(entryname);
            #if SHARPZIPLIBWORKS
            if (FileExists(file))
                DeleteFile(file);

            return new StreamWrapper(new XervBackup.Library.Core.TempFile(), entryname, m_zip);
            #else
            ICSharpCode.SharpZipLib.Zip.ZipEntry ze = new ICSharpCode.SharpZipLib.Zip.ZipEntry(entryname);
            ze.DateTime = lastWrite;

            //Encode filenames as unicode, we do this for all files, to avoid codepage issues
            ze.Flags |= (int)ICSharpCode.SharpZipLib.Zip.GeneralBitFlags.UnicodeText;

            m_stream.PutNextEntry(ze);
            return new StreamWrapper2(m_stream);
            #endif
        }
예제 #44
0
 /// <summary>
 /// Performs an in memory zip of the specified bytes
 /// </summary>
 /// <param name="bytes">The file contents in bytes to be zipped</param>
 /// <param name="zipEntryName">The zip entry name</param>
 /// <returns>The zipped file as a byte array</returns>
 public static byte[] ZipBytes(byte[] bytes, string zipEntryName)
 {
     using (var memoryStream = new MemoryStream())
     using (var stream = new ZipOutputStream(memoryStream))
     {
         var entry = new ZipEntry(zipEntryName);
         stream.PutNextEntry(entry);
         var buffer = new byte[16*1024];
         StreamUtils.Copy(new MemoryStream(bytes), stream, buffer);
         return memoryStream.GetBuffer();
     }
 }
예제 #45
0
        /// <summary>
        /// Create a zip file of the supplied file names and data using a byte array
        /// </summary>
        /// <param name="zipPath">Output location to save the file.</param>
        /// <param name="filenamesAndData">File names and data in a dictionary format.</param>
        /// <returns>True on successfully saving the file</returns>
        public static bool ZipData(string zipPath, IEnumerable<KeyValuePair<string, byte[]>> filenamesAndData)
        {
            var success = true;
            var buffer = new byte[4096];

            try
            {
                //Create our output
                using (var stream = new ZipOutputStream(File.Create(zipPath)))
                {
                    foreach (var file in filenamesAndData)
                    {
                        //Create the space in the zip file:
                        var entry = new ZipEntry(file.Key);
                        //Get a Byte[] of the file data:
                        stream.PutNextEntry(entry);

                        using (var ms = new MemoryStream(file.Value))
                        {
                            int sourceBytes;
                            do
                            {
                                sourceBytes = ms.Read(buffer, 0, buffer.Length);
                                stream.Write(buffer, 0, sourceBytes);
                            }
                            while (sourceBytes > 0);
                        }
                    } // End For Each File.

                    //Close stream:
                    stream.Finish();
                    stream.Close();
                } // End Using
            }
            catch (Exception err)
            {
                Log.Error("QC.Data.ZipData(): " + err.Message);
                success = false;
            }
            return success;
        }
예제 #46
0
 /// <summary>
 /// Zips the specified lines of text into the zipPath
 /// </summary>
 /// <param name="zipPath">The destination zip file path</param>
 /// <param name="zipEntry">The entry name in the zip</param>
 /// <param name="lines">The lines to be written to the zip</param>
 /// <returns>True if successful, otherwise false</returns>
 public static bool ZipData(string zipPath, string zipEntry, IEnumerable<string> lines)
 {
     try
     {
         using (var stream = new ZipOutputStream(File.Create(zipPath)))
         using (var writer = new StreamWriter(stream))
         {
             var entry = new ZipEntry(zipEntry);
             stream.PutNextEntry(entry);
             foreach (var line in lines)
             {
                 writer.WriteLine(line);
             }
         }
         return true;
     }
     catch (Exception err)
     {
         Log.Error(err);
         return false;
     }
 }
예제 #47
0
 /// <summary>
 /// Zips the specified <paramref name="baseFolder"/>.
 /// </summary>
 /// <param name="baseFolder">The folder to zip</param>
 /// <param name="filesToZip">
 /// the files and directories within the <paramref name="baseFolder"/> to include in the zip. 
 /// These names are only matched in the <paramref name="baseFolder"/> but not recursive.
 /// You can use the default globbing (* and ?).
 /// </param>
 /// <param name="filesToIgnore">Names of the files or directories to exclude from zip. Full case sensitive match. No globbing. Directories have a trailing "/".</param>
 public void Zip(string baseFolder, string[] filesToZip, string[] filesToIgnore)
 {
     var baseDir = new DirectoryInfo(baseFolder);
      foreach (var fileMask in filesToZip)
      {
     foreach (var file in baseDir.GetFiles(fileMask, SearchOption.TopDirectoryOnly))
     {
        if (IgnoreFile(baseDir.FullName, file.FullName, filesToIgnore)) continue;
        var zipEntry = new ICSharpCode.SharpZipLib.Zip.ZipEntry(file.Name);
        zipStream.PutNextEntry(zipEntry);
        using (var fileStream = file.OpenRead()) fileStream.CopyTo(zipStream);
     }
     foreach (var subDir in baseDir.GetDirectories(fileMask, SearchOption.TopDirectoryOnly))
     {
        if (IgnoreFile(baseDir.FullName, subDir.FullName, filesToIgnore)) continue;
        ZipDirectory(zipStream, baseDir, subDir, filesToIgnore);
     }
      }
 }
예제 #48
0
 /// <summary>
 /// Zips the specified <paramref name="baseFolder"/>.
 /// </summary>
 /// <param name="fileName">Relative filename in zip.</param>
 /// <param name="contentStream">The content of the file</param>
 public void Zip(string fileName, Stream contentStream)
 {
     var nameTransform = new ICSharpCode.SharpZipLib.Zip.ZipNameTransform();
      var relativeName = nameTransform.TransformFile(fileName);
      var zipEntry = new ICSharpCode.SharpZipLib.Zip.ZipEntry(relativeName);
      zipStream.PutNextEntry(zipEntry);
      contentStream.CopyTo(zipStream);
 }
		internal void AddResources(Dictionary<string, List<ResourceItem>> resources, bool compressedResources)
		{
			Tracer.Info(Tracer.Compiler, "CompilerClassLoader adding resources...");

			// BUG we need to call GetTypeWrapperFactory() to make sure that the assemblyBuilder is created (when building an empty target)
			ModuleBuilder moduleBuilder = this.GetTypeWrapperFactory().ModuleBuilder;
			Dictionary<string, Dictionary<string, ResourceItem>> jars = new Dictionary<string, Dictionary<string, ResourceItem>>();

			foreach (KeyValuePair<string, List<ResourceItem>> kv in resources)
			{
				foreach (ResourceItem item in kv.Value)
				{
					int count = 0;
					string jarName = item.jar;
				retry:
					Dictionary<string, ResourceItem> jar;
					if (!jars.TryGetValue(jarName, out jar))
					{
						jar = new Dictionary<string, ResourceItem>();
						jars.Add(jarName, jar);
					}
					if (jar.ContainsKey(kv.Key))
					{
						jarName = Path.GetFileNameWithoutExtension(item.jar) + "-" + (count++) + Path.GetExtension(item.jar);
						goto retry;
					}
					jar.Add(kv.Key, item);
				}
			}

			foreach (KeyValuePair<string, Dictionary<string, ResourceItem>> jar in jars)
			{
				MemoryStream mem = new MemoryStream();
				using (ICSharpCode.SharpZipLib.Zip.ZipOutputStream zip = new ICSharpCode.SharpZipLib.Zip.ZipOutputStream(mem))
				{
					foreach (KeyValuePair<string, ResourceItem> kv in jar.Value)
					{
						ICSharpCode.SharpZipLib.Zip.ZipEntry zipEntry = new ICSharpCode.SharpZipLib.Zip.ZipEntry(kv.Key);
						if (kv.Value.zipEntry == null)
						{
							zipEntry.CompressionMethod = ICSharpCode.SharpZipLib.Zip.CompressionMethod.Stored;
						}
						else
						{
							zipEntry.Comment = kv.Value.zipEntry.Comment;
							zipEntry.CompressionMethod = kv.Value.zipEntry.CompressionMethod;
							zipEntry.DosTime = kv.Value.zipEntry.DosTime;
							zipEntry.ExternalFileAttributes = kv.Value.zipEntry.ExternalFileAttributes;
							zipEntry.ExtraData = kv.Value.zipEntry.ExtraData;
							zipEntry.Flags = kv.Value.zipEntry.Flags;
						}
						if (compressedResources || zipEntry.CompressionMethod != ICSharpCode.SharpZipLib.Zip.CompressionMethod.Stored)
						{
							zip.SetLevel(9);
							zipEntry.CompressionMethod = ICSharpCode.SharpZipLib.Zip.CompressionMethod.Deflated;
						}
						zip.PutNextEntry(zipEntry);
						if (kv.Value.data != null)
						{
							zip.Write(kv.Value.data, 0, kv.Value.data.Length);
						}
						zip.CloseEntry();
					}
				}
				mem = new MemoryStream(mem.ToArray());
				string name = jar.Key;
				if (options.targetIsModule)
				{
					name = Path.GetFileNameWithoutExtension(name) + "-" + moduleBuilder.ModuleVersionId.ToString("N") + Path.GetExtension(name);
				}
				jarList.Add(name);
				moduleBuilder.DefineManifestResource(name, mem, ResourceAttributes.Public);
			}
		}
        public void ZipAdminFile(string strFile, List<string> filesExtra)
        {
            if (File.Exists(strFile))
            {
                if (GetConfig().ZipAfterIndexed == true)
                {
                    try
                    {
                        string zipFilePath = Path.ChangeExtension(strFile, ".zip");
                        if (File.Exists(zipFilePath)) File.Delete(zipFilePath);

                        if (filesExtra == null)
                        {
                            filesExtra = new List<string>();
                        }
                        if (strFile != null)
                        {
                            filesExtra.Add(strFile);
                        }

                        ICSharpCode.SharpZipLib.Zip.ZipOutputStream strmZipOutputStream = default(ICSharpCode.SharpZipLib.Zip.ZipOutputStream);
                        strmZipOutputStream = new ICSharpCode.SharpZipLib.Zip.ZipOutputStream(File.Create(zipFilePath));

                        if (GetConfig().CollapseFolders)
                        {
                            // minus.gif
                            string f1 = Application.StartupPath + Path.DirectorySeparatorChar + "plus.gif";
                            if (File.Exists(f1)) filesExtra.Add(f1);
                            string f2 = Application.StartupPath + Path.DirectorySeparatorChar + "minus.gif";
                            if (File.Exists(f2)) filesExtra.Add(f2);
                        }

                        if (File.Exists(GetConfig().LogoPath))
                        {
                            filesExtra.Add(GetConfig().LogoPath);
                        }

                        foreach (string filePath in filesExtra)
                        {
                            FileStream strmFile = File.OpenRead(filePath);
                            byte[] abyBuffer = new byte[(int)strmFile.Length - 1 + 1];
                            strmFile.Read(abyBuffer, 0, abyBuffer.Length);

                            ICSharpCode.SharpZipLib.Zip.ZipEntry objZipEntry = new ICSharpCode.SharpZipLib.Zip.ZipEntry(Path.GetFileName(filePath));
                            objZipEntry.DateTime = DateTime.Now;
                            objZipEntry.Size = strmFile.Length;
                            strmFile.Close();

                            strmZipOutputStream.PutNextEntry(objZipEntry);

                            strmZipOutputStream.Write(abyBuffer, 0, abyBuffer.Length);
                        }

                        ///'''''''''''''''''''''''''''''''''
                        // Finally Close strmZipOutputStream
                        ///'''''''''''''''''''''''''''''''''
                        strmZipOutputStream.Finish();
                        strmZipOutputStream.Close();

                        if (GetConfig().ZipAndDeleteFile == true)
                        {
                            File.Delete(strFile);
                        }
                    }
                    catch (System.UnauthorizedAccessException ex)
                    {
                        Debug.WriteLine(ex.ToString());
                    }
                }
            }
        }
예제 #51
0
 /// <summary>
 /// Recursive Zipping of a directory.
 /// </summary>
 /// <param name="zipStream"></param>
 /// <param name="baseDir"></param>
 /// <param name="dir"></param>
 /// <param name="filesToIgnore"></param>
 private static void ZipDirectory(ICSharpCode.SharpZipLib.Zip.ZipOutputStream zipStream, DirectoryInfo baseDir, DirectoryInfo dir, string[] filesToIgnore)
 {
     var nameTransform = new ICSharpCode.SharpZipLib.Zip.ZipNameTransform(baseDir.FullName);
      foreach (var file in dir.GetFiles())
      {
     if (IgnoreFile(baseDir.FullName, file.FullName, filesToIgnore)) continue;
     var relativeName = nameTransform.TransformFile(file.FullName);
     var zipEntry = new ICSharpCode.SharpZipLib.Zip.ZipEntry(relativeName);
     zipStream.PutNextEntry(zipEntry);
     using (var fileStream = file.OpenRead()) fileStream.CopyTo(zipStream);
      }
      foreach (var subDir in dir.GetDirectories())
      {
     if (IgnoreFile(baseDir.FullName, subDir.FullName, filesToIgnore)) continue;
     ZipDirectory(zipStream, baseDir, subDir, filesToIgnore);
      }
 }