public override Stream GetWriteStream(UploadedFile file)
        {
            file.ServerLocation = Path.Combine(HttpContext.Current.Server.MapPath(_location), Path.GetFileNameWithoutExtension(GetValidFileName(file.ClientName)) + ".zip");

            Directory.CreateDirectory(Path.GetDirectoryName(file.ServerLocation));

            FileStream fileS = null;
            ZipOutputStream zipS = null;

            try
            {
                fileS = File.OpenWrite(file.ServerLocation);
                zipS = new ZipOutputStream(fileS);

                zipS.SetLevel(5);

                zipS.PutNextEntry(new ZipEntry(file.ClientName));

                return zipS;
            }
            catch
            {
                if (zipS != null)
                    zipS.Dispose();
                if (fileS != null)
                    fileS.Dispose();

                throw;
            }
        }
Exemple #2
0
        public void CompressFile(string sourcePath, string destinationPath)
        {
            using (ICSharpCode.SharpZipLib.Zip.ZipOutputStream zipStream = new ICSharpCode.SharpZipLib.Zip.ZipOutputStream(File.Create(destinationPath)))
            {
                zipStream.SetLevel(9);

                byte[] buffer = new byte[4096];
                ICSharpCode.SharpZipLib.Zip.ZipEntry entry = new ICSharpCode.SharpZipLib.Zip.ZipEntry(System.IO.Path.GetFileName(sourcePath));

                entry.DateTime = DateTime.Now;
                zipStream.PutNextEntry(entry);

                using (FileStream fs = File.OpenRead(sourcePath))
                {
                    int sourceBytes = 0;
                    do
                    {
                        sourceBytes = fs.Read(buffer, 0, buffer.Length);
                        zipStream.Write(buffer, 0, sourceBytes);
                    } while (sourceBytes > 0);
                }

                zipStream.Finish();
                zipStream.Close();
                zipStream.Dispose();
            }
        }
        //public static void ZipFile(string path, string file2Zip, string zipFileName, string zip, string bldgType)
        public static void ZipFile(string path, string file2Zip, string zipFileName)
        {
            //MemoryStream ms = InitializeGbxml(path + file2Zip, zip, bldgType) as MemoryStream;
            MemoryStream ms = InitializeGbxml(Path.Combine(path , file2Zip)) as MemoryStream;
 
            string compressedFile =Path.Combine(path, zipFileName);
            if (File.Exists(compressedFile))
            {
                File.Delete(compressedFile);
            }
            Crc32 objCrc32 = new Crc32();
            ZipOutputStream strmZipOutputStream = new ZipOutputStream(File.Create(compressedFile));
            strmZipOutputStream.SetLevel(9);

            byte[] gbXmlBuffer = new byte[ms.Length];
            ms.Read(gbXmlBuffer, 0, gbXmlBuffer.Length);

            ZipEntry objZipEntry = new ZipEntry(file2Zip);

            objZipEntry.DateTime = DateTime.Now;
            objZipEntry.Size = ms.Length;
            ms.Close();
            objCrc32.Reset();
            objCrc32.Update(gbXmlBuffer);
            objZipEntry.Crc = objCrc32.Value;
            strmZipOutputStream.PutNextEntry(objZipEntry);
            strmZipOutputStream.Write(gbXmlBuffer, 0, gbXmlBuffer.Length);
            strmZipOutputStream.Finish();
            strmZipOutputStream.Close();
            strmZipOutputStream.Dispose();
        }
        public static void ZipFiles(string inputFolderPath, string outputPathAndFile, string password)
        {
            ArrayList ar = GenerateFileList(inputFolderPath); // generate file list
            int TrimLength = (Directory.GetParent(inputFolderPath)).ToString().Length;
            // find number of chars to remove 	// from orginal file path
            TrimLength += 1; //remove '\'
            FileStream ostream;
            byte[] obuffer;
            string outPath = outputPathAndFile;
            ZipOutputStream oZipStream = new ZipOutputStream(File.Create(outPath)); // create zip stream
            if (password != null && password != String.Empty)
                oZipStream.Password = password;
            oZipStream.SetLevel(9); // maximum compression
            ZipEntry oZipEntry;
            foreach (string Fil in ar) // for each file, generate a zipentry
            {
                oZipEntry = new ZipEntry(Fil.Remove(0, TrimLength));
                oZipStream.PutNextEntry(oZipEntry);

                if (!Fil.EndsWith(@"/")) // if a file ends with '/' its a directory
                {
                    ostream = File.OpenRead(Fil);
                    obuffer = new byte[ostream.Length];
                    ostream.Read(obuffer, 0, obuffer.Length);
                    oZipStream.Write(obuffer, 0, obuffer.Length);
                }
            }
            oZipStream.Finish();
            oZipStream.Close();
            oZipStream.Dispose();
        }
Exemple #5
0
        /// <summary>
        /// Creates a ZIP archive using the specified dictionary.  
        /// The keys in the dictionary are the paths of the files as they should appear in the archive.  
        /// The values in the dictionary are the absolute paths to the files on the local filesystem.
        /// </summary>
        /// <exception cref="UnauthorizedAccessException">The caller does not have the required permission.-or- <paramref name="archiveFilePath" /> specified a file that is read-only. </exception>
        /// <exception cref="PathTooLongException">The specified path, file name, or both exceed the system-defined maximum length. For example, on Windows-based platforms, paths must be less than 248 characters, and file names must be less than 260 characters. </exception>
        /// <exception cref="DirectoryNotFoundException">The specified path is invalid (for example, it is on an unmapped drive). </exception>
        /// <exception cref="IOException">An I/O error occurred while creating the file. </exception>
        /// <exception cref="NotSupportedException"><paramref name="archiveFilePath" /> is in an invalid format. </exception>
        /// <exception cref="SecurityException">The caller does not have the required permission. </exception>
        /// <exception cref="FileNotFoundException">One of the elements within <paramref name="zipContents" /> points to a file that does not exist. </exception>
        public static void CreateZip(String archiveFilePath, Dictionary<String, String> zipContents)
        {
            using (FileStream fsOut = File.Create(archiveFilePath))
            {
                var zipStream = new ZipOutputStream(fsOut);
                zipStream.SetLevel(9); // Compression Level: Valid range is 0-9, with 9 being the highest level of compression.

                foreach (var content in zipContents)
                {
                    String archivePath = content.Key; // The location of the file as it appears in the archive.
                    String filePath = content.Value; // The location of the file as it exists on disk.

                    // Skip files that have no path.
                    if (String.IsNullOrWhiteSpace(filePath)) { continue; }

                    // Skip files that do not exist.
                    if (!File.Exists(filePath)) { continue; }

                    FileInfo fi = new FileInfo(filePath);

                    // Makes the name in zip based on the folder
                    String entryName = archivePath;

                    // Removes drive from name and fixes slash direction
                    entryName = ZipEntry.CleanName(entryName); 
                    
                    
                    var newEntry = new ZipEntry(entryName);
                    newEntry.DateTime = fi.LastWriteTime; // Note: Zip format stores 2 second granularity
                    newEntry.Size = fi.Length;
                    zipStream.PutNextEntry(newEntry);

                    // Zip the file in buffered chunks
                    // the "using" will close the stream even if an exception occurs
                    var buffer = new byte[4096];
                    using (FileStream streamReader = File.OpenRead(filePath))
                    {
                        StreamUtils.Copy(streamReader, zipStream, buffer);
                    }
                    zipStream.CloseEntry();
                }

                zipStream.IsStreamOwner = true; // Makes the Close also Close the underlying stream
                zipStream.Close();
                zipStream.Dispose();
            }
        }
Exemple #6
0
        public static Boolean ZipFile(String filePath, String zipFile)
        {
            if (!File.Exists(filePath))
            {
                Debug.WriteLine("Cannot find file '{0}'", filePath);
                return(false);
            }

            try
            {
                using (ICSharpCode.SharpZipLib.Zip.ZipOutputStream zipStream = new ICSharpCode.SharpZipLib.Zip.ZipOutputStream(File.Create(zipFile)))
                {
                    zipStream.SetLevel(9);         //0~9

                    byte[] buffer = new byte[4096];
                    ICSharpCode.SharpZipLib.Zip.ZipEntry entry = new ICSharpCode.SharpZipLib.Zip.ZipEntry(System.IO.Path.GetFileName(filePath));

                    entry.DateTime = DateTime.Now;
                    zipStream.PutNextEntry(entry);

                    using (FileStream fs = File.OpenRead(filePath))
                    {
                        int sourceBytes = 0;
                        do
                        {
                            sourceBytes = fs.Read(buffer, 0, buffer.Length);
                            zipStream.Write(buffer, 0, sourceBytes);
                        } while (sourceBytes > 0);
                    }

                    zipStream.Finish();
                    zipStream.Close();
                    zipStream.Dispose();
                }

                if (File.Exists(zipFile))
                {
                    return(true);
                }
            }
            catch (Exception ex)
            {
                Debug.WriteLine("Exception during processing {0}", ex);
            }
            return(false);
        }
 private String CompressionDossier(String pFichier)
 {
     try
     {
         if (Directory.Exists(pFichier) == true)
         {
             //System.IO.Compression.GZipStream gzip = new System.IO.Compression.GZipStream();
             using (var s = new ICSharpCode.SharpZipLib.Zip.ZipOutputStream(File.Create(String.Format("{0}.zip", pFichier))))
             {
                 s.SetLevel(9);
                 var buffer = new byte[4096];
                 var entry  = new ICSharpCode.SharpZipLib.Zip.ZipEntry(pFichier)
                 {
                     DateTime = DateTime.Now
                 };
                 s.PutNextEntry(entry);
                 using (StreamReader fs = new StreamReader(pFichier))
                 {
                     int sourceBytes;
                     do
                     {
                         sourceBytes = fs.Read();
                         s.Write(buffer, 0, sourceBytes);
                     } while (sourceBytes > 0);
                 }
                 s.Finish();
                 s.Close();
                 s.Dispose();
                 pFichier = string.Format("{0}.zip", pFichier);
             }
             //}
         }
         return(pFichier);
     }
     catch (Exception ex)
     {
         throw ex;
     }
 }
Exemple #8
0
        // Save mosaic data.
        internal void SaveMosaicCacheFile()
        {
            if (this.threadController != null)
                this.threadController.ReportThreadStarted(this, "Saving Tiles");

            string tempFilePath = Path.GetTempFileName();

            try
            {
                this.oZipStream = new ZipOutputStream(System.IO.File.Create(tempFilePath));
            }
            catch(Exception e)
            {
                MessageBox.Show(e.Message);
                return;
            }

            this.oZipStream.SetLevel(2); // 9 = maximum compression level

            ZipEntry oZipEntry = new ZipEntry("info.txt");
            this.oZipStream.PutNextEntry(oZipEntry);

            StreamWriter sw = new StreamWriter(oZipStream);
            TileSaver.SaveMosaicHeader(MosaicWindow.MosaicInfo, sw);

            ThumbnailMapCollection mapCollection = new ThumbnailMapCollection(MosaicWindow.MosaicInfo.Items[0].Thumbnail.Width,
                                                MosaicWindow.MosaicInfo.Items[0].Thumbnail.Height);

            mapCollection.MapFilled += new ThumbnailMapCollectionEventHandler(OnMapFilled);

            int count = 1;
            int requiredMaps = (MosaicWindow.MosaicInfo.Items.Count / ThumbnailMap.MaxSize) + 1;

            foreach (Tile tile in MosaicWindow.MosaicInfo.Items) // For each file, generate a zipentry
            {
                if (this.threadController.ThreadAborted)
                    return;

                mapCollection.AddThumbnail(tile);

                if (this.threadController != null)
                    threadController.ReportThreadPercentage(this, "Creating Tile Maps",
                        count++, MosaicWindow.MosaicInfo.Items.Count);
            }

            // Final map may not get completly filled
            // if not then save it here

            if(mapCollection.Maps.Count <= requiredMaps) {
                ThumbnailMapCollectionEventArgs thumbnailEventArgs
                    = new ThumbnailMapCollectionEventArgs(mapCollection.Last);

                OnMapFilled(mapCollection, thumbnailEventArgs);
            }

            mapCollection.Dispose();
            oZipStream.Finish();
            oZipStream.Dispose();
            oZipStream.Close();

            try
            {
                File.Delete(MosaicWindow.MosaicInfo.TileReader.GetCacheFilePath());
                File.Copy(tempFilePath, MosaicWindow.MosaicInfo.TileReader.GetCacheFilePath());
            }
            catch (Exception)
            {

            }

            //File.SetAttributes(this.filePath, FileAttributes.Hidden);

            if (this.threadController != null)
                this.threadController.ReportThreadCompleted(this, "Cache Saved", false);

            GC.Collect();
        }
        public static void CreateZipResponseOld(List<string> ZipFileList ,HttpResponse Response,string ZipFileName,string TempFolder)
        {

            Response.Clear();
            Response.ContentType = "application/x-zip-compressed";
            Response.AppendHeader("content-disposition", "attachment; filename=\"" + ZipFileName + ".zip\"");



            ZipEntry entry = default(ZipEntry);
            const int size = 409600;
            byte[] bytes = new byte[size + 1];
            int numBytes = 0;

            FileStream fs = null;
            ZipOutputStream zipStream = new ZipOutputStream(Response.OutputStream);
            try
            {
                try
                {
                    zipStream.IsStreamOwner = false;
                    zipStream.SetLevel(0);
                    foreach (string file in ZipFileList)
                    {
                        string folderName = ZipFileName + @"\";
                        entry =
                            new ZipEntry(folderName +
                                         ZipEntry.CleanName(file.Contains(ZipFileName + "\\")
                                                                ? file.Substring(file.LastIndexOf(ZipFileName + "\\") +
                                                                                 ZipFileName.Length + 1)
                                                                : file.Substring(file.LastIndexOf("\\") + 1)));
                        zipStream.PutNextEntry(entry);

                        fs = System.IO.File.OpenRead(file);
                        numBytes = fs.Read(bytes, 0, size);
                        while (numBytes > 0)
                        {
                            zipStream.Write(bytes, 0, numBytes);
                            numBytes = fs.Read(bytes, 0, size);
                            if (Response.IsClientConnected == false)
                            {
                                break;
                            }
                            Response.Flush();
                        }
                        fs.Close();
                    }

                    foreach (string fileName in Directory.GetFiles(TempFolder))
                    {
                        File.Delete(fileName);
                    }
                    Directory.Delete(TempFolder);

                }
                catch (Exception ex)
                {
                    throw ex;
                }
                finally
                {
                    zipStream.Finish();
                    zipStream.Close();
                    zipStream.Dispose();
                    Response.End();
                }
            }
            catch (ThreadAbortException err)
            {
                throw err;
            }
            catch (Exception err)
            {
                throw err;
            }
        }
        internal void Serialize(string filePath)
        {
            Stream stream = new MemoryStream();
            System.Windows.Forms.Cursor cursor = System.Windows.Forms.Cursor.Current;
            try
            {
                Serialize(stream, true);
                stream.Position = 0;

                byte[] buffer = new byte[8192];
                if (".xml".Equals(Path.GetExtension(filePath).ToLower()))
                {
            #if DEBUG
                    FileStream fWritter = File.Create(filePath);
                    StreamUtils.Copy(stream, fWritter, buffer);
                    fWritter.Close();
            #else
                    throw new Exception("XML format not supported by current version");
            #endif
                }
                else
                {
                    FileStream fs = File.Create(filePath);
                    BinaryFormatter bformatter = new BinaryFormatter();
                    bformatter.Serialize(fs, "version=7.14");
                    using (ZipOutputStream s = new ZipOutputStream(fs))
                    {
                        try
                        {
                            System.Windows.Forms.Cursor.Current = System.Windows.Forms.Cursors.WaitCursor;
                            s.Password = "******";
                            if (model.HasResults)
                                s.SetLevel(5); // 0 (store only) to 9 (best compression)
                            else
                                s.SetLevel(9); // 0 (store only) to 9 (best compression)
                            ZipEntry entry = new ZipEntry(Path.GetFileName("[Empty]"));
                            s.PutNextEntry(entry);
                            StreamUtils.Copy(stream, s, buffer);
                        }
                        finally
                        {
                            s.Flush();
                            s.Finish();
                            s.Close();
                            s.Dispose();
                        }
                    }
                }
            }
            finally
            {
                stream.Close();
                System.Windows.Forms.Cursor.Current = cursor;
            }
        }
Exemple #11
0
        /// <summary>
        /// Zips the package.
        /// </summary>
        /// <param name="Path">The path.</param>
        /// <param name="savePath">The save path.</param>
        public static void ZipPackage(string Path, string savePath) {
            string OutPath = savePath;

            ArrayList ar = GenerateFileList(Path);
            // generate file list
            // find number of chars to remove from orginal file path
            int TrimLength = (Directory.GetParent(Path)).ToString().Length;

            TrimLength += 1;

            //remove '\'
            FileStream ostream;

            byte[] obuffer;

            ZipOutputStream oZipStream = new ZipOutputStream(System.IO.File.Create(OutPath));
            // create zip stream


            oZipStream.SetLevel(9);
            // 9 = maximum compression level
            ZipEntry oZipEntry;

            foreach (string Fil in ar) // for each file, generate a zipentry
            {
                oZipEntry = new ZipEntry(Fil.Remove(0, TrimLength));
                oZipStream.PutNextEntry(oZipEntry);


                if (!Fil.EndsWith(@"/")) // if a file ends with '/' its a directory
                {
                    ostream = File.OpenRead(Fil);

                    obuffer = new byte[ostream.Length];

                    // byte buffer
                    ostream.Read(obuffer, 0, obuffer.Length);

                    oZipStream.Write(obuffer, 0, obuffer.Length);
                    ostream.Close();
                }
            }
            oZipStream.Finish();
            oZipStream.Close();
            oZipStream.Dispose();
            oZipStream = null;

            oZipEntry = null;


            ostream = null;
            ar.Clear();
            ar = null;
        }
		} // proc CreateZipStream

		private void CloseZipStream(FileWrite zipStream, ZipOutputStream zip)
		{
			if (zip != null)
			{
				zip.Flush();
				zip.Dispose();
			}
			if (zipStream != null)
				zipStream.Dispose();
		} // proc CloseZipStream
Exemple #13
0
        public void GenerateZip(string zipFileFolder, string tmpFolderPath, List<TreeEntryChanges> filesToBeBackedUp, List<TreeEntryChanges> filesToBeDeployed, string olderVersion, string newerVersion)
        {
            if (!Directory.Exists(zipFileFolder))
            {
                Directory.CreateDirectory(zipFileFolder);
            }

            string zipFileDestination = string.Format("{0}UPDATE_v{1}-v{2}_{3}.zip", zipFileFolder, olderVersion, newerVersion, DateTime.Now.ToString("dd_MM_yyyy_HH_mm"));
            if (File.Exists(zipFileDestination))
            {
                File.Delete(zipFileDestination);
            }

            ZipOutputStream zipOutputStream = new ZipOutputStream(File.Create(zipFileDestination));

            if (filesToBeBackedUp != null)
            {
                Logger.Instance.Log("----- STARTING TO ZIP BACKUP -----");
                foreach (TreeEntryChanges fileChanges in filesToBeBackedUp)
                {
                    AddToZip(zipOutputStream, string.Format("{0}{1}\\", tmpFolderPath, "backup"), fileChanges.OldPath, "backup");
                }
                Logger.Instance.Log("----- FINISHED ZIPPING BACKUP -----");
            }

            if (filesToBeDeployed != null)
            {
                Logger.Instance.Log("----- STARTING TO ZIP DEPLOY -----");
                foreach (TreeEntryChanges fileChanges in filesToBeDeployed)
                {
                    AddToZip(zipOutputStream, string.Format("{0}{1}\\", tmpFolderPath, "deploy"), fileChanges.Path, "deploy");
                }
                Logger.Instance.Log("----- FINISHED ZIPPING DEPLOY -----");
            }

            FileInfo logFileInfo = new FileInfo(Logger.LogFilePath);
            ZipEntry logZipEntry = new ZipEntry(logFileInfo.Name);

            logZipEntry.Size = logFileInfo.Length;

            zipOutputStream.PutNextEntry(logZipEntry);

            using (FileStream streamReader = File.OpenRead(logFileInfo.FullName))
            {
                StreamUtils.Copy(streamReader, zipOutputStream, new byte[BufferSize]);
            }
            zipOutputStream.CloseEntry();

            zipOutputStream.Dispose();
        }
    public override Stream GetOutputStream(UploadedFile file)
    {
        FileStream fileS = null;
        ZipOutputStream zipS = null;

        try
        {
            string outputPath = GetZipPath(file);

            Directory.CreateDirectory(Path.GetDirectoryName(outputPath));

            fileS = File.OpenWrite(outputPath);
            zipS = new ZipOutputStream(fileS);

            zipS.SetLevel(5);

            zipS.PutNextEntry(new ZipEntry(file.ClientName));

            file.LocationInfo[FileNameKey] = outputPath;

            return zipS;
        }
        catch
        {
            if (fileS != null)
                fileS.Dispose();

            if (zipS != null)
                zipS.Dispose();

            return null;
        }
    }
        private Stream CompressToZip(NameValueCollection entries)
        {
            var stream = TempStream.Create();
            using (var zip = new ZipOutputStream(stream))
            {
                zip.IsStreamOwner = false;
                zip.SetLevel(3);
                zip.UseZip64 = UseZip64.Off;

                foreach (var title in entries.AllKeys)
                {
                    if (Canceled)
                    {
                        zip.Dispose();
                        stream.Dispose();
                        return null;
                    }

                    var counter = 0;
                    foreach (var path in entries[title].Split(','))
                    {
                        var newtitle = title;
                        if (0 < counter)
                        {
                            var suffix = " (" + counter + ")";
                            newtitle = 0 < newtitle.IndexOf('.')
                                           ? newtitle.Insert(newtitle.LastIndexOf('.'), suffix)
                                           : newtitle + suffix;
                        }
                        var zipentry = new ZipEntry(newtitle) {DateTime = DateTime.UtcNow};
                        lock (zip)
                        {
                            ZipConstants.DefaultCodePage = Thread.CurrentThread.CurrentCulture.TextInfo.OEMCodePage;
                            zip.PutNextEntry(zipentry);
                        }
                        if (!string.IsNullOrEmpty(path))
                        {
                            var file = Global.DaoFactory.GetFileDao().GetFile(path);
                            if (file.ConvertedType != null)
                            {
                                //Take from converter
                                try
                                {
                                    using (var readStream = DocumentUtils.GetConvertedFile(file))
                                    {
                                        if (readStream != null)
                                        {
                                            readStream.StreamCopyTo(zip);
                                        }
                                    }
                                }
                                catch
                                {
                                }
                            }
                            else
                            {
                                using (var readStream = Global.DaoFactory.GetFileDao().GetFileStream(file))
                                {
                                    readStream.StreamCopyTo(zip);
                                }
                            }
                        }
                        counter++;
                    }
                    lock (zip)
                    {
                        ZipConstants.DefaultCodePage = Thread.CurrentThread.CurrentCulture.TextInfo.OEMCodePage;
                        zip.CloseEntry();
                    }
                    ProgressStep();
                }
                return stream;
            }
        }