Ejemplo n.º 1
0
        /// <summary>
        /// Creates a ZIP archive, returned as a <see cref="ZipOutputStream"/>, containing the specified <paramref name="content"/>
        /// and having the specified <paramref name="fileNameForZip" />. The archive is created in memory and is not stored on disk.
        /// </summary>
        /// <param name="content">The text to be added to the ZIP archive.</param>
        /// <param name="fileNameForZip">The name to be given to the <paramref name="content" /> within the ZIP archive.</param>
        /// <returns>Returns a <see cref="MemoryStream"/> of a ZIP archive that contains the specified <paramref name="content" />.</returns>
        public static Stream CreateZipStream(string content, string fileNameForZip)
        {
            MemoryStream ms = new MemoryStream();
            ZipOutputStream zos = new ZipOutputStream(ms);

            zos.SetLevel(ZIP_COMPRESSION_LEVEL);

            AddFileZipEntry(zos, content, fileNameForZip);

            zos.Finish();

            return ms;
        }
Ejemplo n.º 2
0
        public static bool ZipFilesAndChildFiles(string folderPath, string zipFileName)
        {
            ZipOutputStream zipStream = null;

            try
            {
                if (!Directory.Exists(folderPath))
                {
                    Console.WriteLine("Cannot find directory '{0}'", folderPath);
                    return(false);
                }

                if (folderPath[folderPath.Length - 1] != System.IO.Path.DirectorySeparatorChar)
                {
                    folderPath += System.IO.Path.DirectorySeparatorChar;
                }

                string tmp         = folderPath.Substring(0, folderPath.LastIndexOf("\\"));
                string entryFolder = tmp.Substring(tmp.LastIndexOf("\\") + 1);


                if (!zipFileName.ToLower().EndsWith(ConstHelper.ZIPExtension))
                {
                    zipFileName += ConstHelper.ZIPExtension;
                }

                zipStream = new ZipOutputStream(File.Create(zipFileName));
                zipStream.SetLevel(9);

                ZipDirectory(folderPath, zipStream, entryFolder);
                return(true);
            }
            catch (Exception ex)
            {
                throw ex;
            }
            finally
            {
                zipStream?.Finish();
                zipStream?.Close();
            }
        }
Ejemplo n.º 3
0
    public static void Main(string[] args)
    {
        // Perform some simple parameter checking.  More could be done
        // like checking the target file name is ok, disk space, and lots
        // of other things, but for a demo this covers some obvious traps.
        if (args.Length < 2)
        {
            Console.WriteLine("Usage: CreateZipFile Path ZipFile");
            return;
        }

        if (!Directory.Exists(args[0]))
        {
            Console.WriteLine("Cannot find directory '{0}'", args[0]);
            return;
        }

        try
        {
            // Depending on the directory this could be very large and would require more attention
            // in a commercial package.
            string[] filenames = Directory.GetFiles(args[0]);

            // 'using' statements guarantee the stream is closed properly which is a big source
            // of problems otherwise.  Its exception safe as well which is great.
            using (ZipOutputStream s = new ZipOutputStream(File.Create(args[1]))) {
                s.SetLevel(9);                 // 0 - store only to 9 - means best compression

                byte[] buffer = new byte[4096];

                foreach (string file in filenames)
                {
                    // Using GetFileName makes the result compatible with XP
                    // as the resulting path is not absolute.
                    ZipEntry entry = new ZipEntry(Path.GetFileName(file));

                    // Setup the entry data as required.

                    // Crc and size are handled by the library for seakable streams
                    // so no need to do them here.

                    // Could also use the last write time or similar for the file.
                    entry.DateTime = DateTime.Now;
                    s.PutNextEntry(entry);

                    using (FileStream fs = File.OpenRead(file)) {
                        // Using a fixed size buffer here makes no noticeable difference for output
                        // but keeps a lid on memory usage.
                        int sourceBytes;
                        do
                        {
                            sourceBytes = fs.Read(buffer, 0, buffer.Length);
                            s.Write(buffer, 0, sourceBytes);
                        } while (sourceBytes > 0);
                    }
                }

                // Finish/Close arent needed strictly as the using statement does this automatically

                // Finish is important to ensure trailing information for a Zip file is appended.  Without this
                // the created file would be invalid.
                s.Finish();

                // Close is important to wrap things up and unlock the file.
                s.Close();
            }
        }
        catch (Exception ex)
        {
            Console.WriteLine("Exception during processing {0}", ex);

            // No need to rethrow the exception as for our purposes its handled.
        }
    }
Ejemplo n.º 4
0
        public static void CreateInstaller(string input, string output, Func <string, bool> excludeFromCompression)
        {
            Console.Write("Creating install package " + output + " ");

            if (!input.EndsWith("\\", StringComparison.OrdinalIgnoreCase))
            {
                input += "\\";
            }
            int trimOffset = (string.IsNullOrEmpty(input) ? Path.GetPathRoot(input).Length : input.Length);

            List <string> fileSystemEntries = new List <string>();

            fileSystemEntries.AddRange(Directory.GetDirectories(input, "*", SearchOption.AllDirectories).Select(d => d + "\\"));
            fileSystemEntries.AddRange(Directory.GetFiles(input, "*", SearchOption.AllDirectories));


            using (var outputStream = new FileStream(output, FileMode.Create, FileAccess.Write, FileShare.None))
            {
                using (var compressor = new ZipOutputStream(outputStream))
                {
                    compressor.SetLevel(9);
                    var data      = new byte[4194304];
                    int milestone = fileSystemEntries.Count / 10;
                    int i         = 0;

                    foreach (var filePath in fileSystemEntries)
                    {
                        if (i++ % milestone == 0)
                        {
                            Console.Write('.');
                        }

                        if (excludeFromCompression(filePath))
                        {
                            continue;
                        }

                        if (filePath.EndsWith("\\", StringComparison.OrdinalIgnoreCase))
                        {
                            var directoryInfo = new DirectoryInfo(filePath);
                            compressor.PutNextEntry(new ZipEntry(filePath.Substring(trimOffset))
                            {
                                DateTime = directoryInfo.LastWriteTimeUtc
                            });
                            continue;
                        }
                        else
                        {
                            var fileInfo = new FileInfo(filePath);
                            compressor.PutNextEntry(new ZipEntry(filePath.Substring(trimOffset))
                            {
                                DateTime = fileInfo.LastWriteTimeUtc,
                                Size     = fileInfo.Length
                            });
                        }

                        using (var inputStream = File.OpenRead(filePath))
                        {
                            int bytesRead;
                            while ((bytesRead = inputStream.Read(data, 0, data.Length)) > 0)
                            {
                                compressor.Write(data, 0, bytesRead);
                            }
                        }
                    }
                    Console.WriteLine();
                    compressor.Finish();
                }
            }
        }
Ejemplo n.º 5
0
        string BuildPackageInternal(IProgressStatus monitor, bool debugSymbols, string targetDirectory, string filePath)
        {
            AddinDescription conf = registry.GetAddinDescription(monitor, filePath);

            if (conf == null)
            {
                monitor.ReportError("Could not read add-in file: " + filePath, null);
                return(null);
            }

            string basePath = Path.GetDirectoryName(Path.GetFullPath(filePath));

            if (targetDirectory == null)
            {
                targetDirectory = basePath;
            }

            // Generate the file name

            string name;

            if (conf.LocalId.Length == 0)
            {
                name = Path.GetFileNameWithoutExtension(filePath);
            }
            else
            {
                name = conf.LocalId;
            }
            name = Addin.GetFullId(conf.Namespace, name, conf.Version);
            name = name.Replace(',', '_').Replace(".__", ".");

            string outFilePath = Path.Combine(targetDirectory, name) + ".mpack";

            ZipOutputStream s = new ZipOutputStream(File.Create(outFilePath));

            s.SetLevel(5);

            // Generate a stripped down description of the add-in in a file, since the complete
            // description may be declared as assembly attributes

            XmlDocument doc = new XmlDocument();

            doc.PreserveWhitespace = false;
            doc.LoadXml(conf.SaveToXml().OuterXml);
            CleanDescription(doc.DocumentElement);
            MemoryStream  ms = new MemoryStream();
            XmlTextWriter tw = new XmlTextWriter(ms, System.Text.Encoding.UTF8);

            tw.Formatting = Formatting.Indented;
            doc.WriteTo(tw);
            tw.Flush();
            byte[] data = ms.ToArray();

            var infoEntry = new ZipEntry("addin.info")
            {
                Size = data.Length
            };

            s.PutNextEntry(infoEntry);
            s.Write(data, 0, data.Length);
            s.CloseEntry();

            // Now add the add-in files

            var files = new HashSet <string> ();

            files.Add(Path.GetFileName(Util.NormalizePath(filePath)));

            foreach (string f in conf.AllFiles)
            {
                var file = Util.NormalizePath(f);
                files.Add(file);
                if (debugSymbols)
                {
                    if (File.Exists(Path.ChangeExtension(file, ".pdb")))
                    {
                        files.Add(Path.ChangeExtension(file, ".pdb"));
                    }
                    else if (File.Exists(file + ".mdb"))
                    {
                        files.Add(file + ".mdb");
                    }
                }
            }

            foreach (var prop in conf.Properties)
            {
                try {
                    var file = Util.NormalizePath(prop.Value);
                    if (File.Exists(Path.Combine(basePath, file)))
                    {
                        files.Add(file);
                    }
                } catch {
                    // Ignore errors
                }
            }

            //add satellite assemblies for assemblies in the list
            var satelliteFinder = new SatelliteAssemblyFinder();

            foreach (var f in files.ToList())
            {
                foreach (var satellite in satelliteFinder.FindSatellites(Path.Combine(basePath, f)))
                {
                    var relativeSatellite = satellite.Substring(basePath.Length + 1);
                    files.Add(relativeSatellite);
                }
            }

            monitor.Log("Creating package " + Path.GetFileName(outFilePath));

            foreach (string file in files)
            {
                string fp = Path.Combine(basePath, file);
                using (FileStream fs = File.OpenRead(fp)) {
                    byte[] buffer = new byte [fs.Length];
                    fs.Read(buffer, 0, buffer.Length);

                    var fileName = Path.DirectorySeparatorChar == '\\' ? file.Replace('\\', '/') : file;
                    var entry    = new ZipEntry(fileName)
                    {
                        Size = fs.Length
                    };
                    s.PutNextEntry(entry);
                    s.Write(buffer, 0, buffer.Length);
                    s.CloseEntry();
                }
            }

            s.Finish();
            s.Close();
            return(outFilePath);
        }
Ejemplo n.º 6
0
 public void AddEntryAfterFinish()
 {
     var ms = new MemoryStream();
     var s = new ZipOutputStream(ms);
     s.Finish();
     s.PutNextEntry(new ZipEntry("dummyfile.tst"));
 }
Ejemplo n.º 7
0
    public static void TestZippedStream(int len, int ziplevel)
    {
      DateTime t1, t2;
      TimeSpan dt;

      Foo o = new Foo();
      o.Fill(len);

      System.IO.FileStream zipoutfile = System.IO.File.Create(@"C:\temp\xmlteststream01.xml.zip");
      ZipOutputStream ZipStream = new ZipOutputStream(zipoutfile);
      ZipEntry ZipEntry = new ZipEntry("Table/Table1.xml");
      ZipStream.PutNextEntry(ZipEntry);
      ZipStream.SetLevel(ziplevel);

      XmlStreamSerializationInfo info = new XmlStreamSerializationInfo();
      t1 = DateTime.Now;
      info.BeginWriting(ZipStream);
      info.AddValue("FooNode",o);
      info.EndWriting();
      ZipStream.Finish();
      ZipStream.Close();
      zipoutfile.Close();

      t2 = DateTime.Now;
      dt = t2-t1;
      Console.WriteLine("Document saved, duration {0}.",dt);

      t1 = DateTime.Now;
      ZipFile zipfile = new ZipFile(@"C:\temp\xmlteststream01.xml.zip");
      System.IO.Stream zipinpstream = zipfile.GetInputStream(new ZipEntry("Table/Table1.xml"));
      XmlStreamDeserializationInfo info3 = new XmlStreamDeserializationInfo();
      info3.BeginReading(zipinpstream);
      Foo o3 = (Foo)info3.GetValue(null);
      info3.EndReading();
      zipinpstream.Close();
      zipfile.Close();
      t2 = DateTime.Now;
      dt = t2-t1;
      Console.WriteLine("Document restored, duration {0}.",dt);
      o3.EnsureEquality(len);
    }
        /// -----------------------------------------------------------------------------
        /// <summary>
        /// Exports the selected portal
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        /// <remarks>
        /// Template will be saved in Portals\_default folder.
        /// An extension of .template will be added to filename if not entered
        /// </remarks>
        /// <history>
        ///     [VMasanas]	23/09/2004	Created
        ///     [cnurse]	11/08/2004	Addition of files to template
        ///     [aprasad]	1/17/2011	New setting AutoAddPortalAlias
        /// </history>
        /// -----------------------------------------------------------------------------
        private void cmdExport_Click(Object sender, EventArgs e)
        {
            try
            {
                // Validations
                bool isValid = true;

                // Verify all ancestor pages are selected
                foreach (RadTreeNode page in ctlPages.CheckedNodes)
                {
                    if (page.ParentNode != null && page.ParentNode.Value != "-1" && !page.ParentNode.Checked)
                    {
                        isValid = false;
                    }
                }
                if (!isValid)
                {
                    UI.Skins.Skin.AddModuleMessage(this, LocalizeString("ErrorAncestorPages"), ModuleMessage.ModuleMessageType.RedError);
                }

                if (ctlPages.CheckedNodes.Count == 0)
                {
                    isValid = false;
                    UI.Skins.Skin.AddModuleMessage(this, LocalizeString("ErrorPages"), ModuleMessage.ModuleMessageType.RedError);
                }

                if (!Page.IsValid || !isValid)
                {
                    return;
                }

                var settings = new XmlWriterSettings();
                settings.ConformanceLevel   = ConformanceLevel.Fragment;
                settings.OmitXmlDeclaration = true;
                settings.Indent             = true;

                var filename = Globals.HostMapPath + txtTemplateName.Text;
                if (!filename.EndsWith(".template"))
                {
                    filename += ".template";
                }
                XmlWriter writer = XmlWriter.Create(filename, settings);

                writer.WriteStartElement("portal");
                writer.WriteAttributeString("version", "5.0");

                //Add template description
                writer.WriteElementString("description", Server.HtmlEncode(txtDescription.Text));

                //Serialize portal settings
                var portal = PortalController.Instance.GetPortal(Convert.ToInt32(cboPortals.SelectedValue));

                SerializePortalSettings(writer, portal);
                SerializeEnabledLocales(writer, portal);
                SerializeExtensionUrlProviders(writer, portal.PortalID);

                if (chkProfile.Checked)
                {
                    //Serialize Profile Definitions
                    SerializeProfileDefinitions(writer, portal);
                }

                if (chkModules.Checked)
                {
                    //Serialize Portal Desktop Modules
                    DesktopModuleController.SerializePortalDesktopModules(writer, portal.PortalID);
                }

                if (chkRoles.Checked)
                {
                    //Serialize Roles
                    RoleController.SerializeRoleGroups(writer, portal.PortalID);
                }

                //Serialize tabs
                SerializeTabs(writer, portal);

                if (chkFiles.Checked)
                {
                    //Create Zip File to hold files
                    var resourcesFile = new ZipOutputStream(File.Create(filename + ".resources"));
                    resourcesFile.SetLevel(6);

                    //Serialize folders (while adding files to zip file)
                    SerializeFolders(writer, portal, ref resourcesFile);

                    //Finish and Close Zip file
                    resourcesFile.Finish();
                    resourcesFile.Close();
                }
                writer.WriteEndElement();

                writer.Close();

                UI.Skins.Skin.AddModuleMessage(this, "", string.Format(Localization.GetString("ExportedMessage", LocalResourceFile), filename), ModuleMessage.ModuleMessageType.GreenSuccess);
            }
            catch (Exception exc)
            {
                Exceptions.ProcessModuleLoadException(this, exc);
            }
        }
Ejemplo n.º 9
0
        public void ParameterHandling()
        {
            var buffer = new byte[10];
            var emptyBuffer = new byte[0];

            var ms = new MemoryStream();
            var outStream = new ZipOutputStream(ms);
            outStream.IsStreamOwner = false;
            outStream.PutNextEntry(new ZipEntry("Floyd"));
            outStream.Write(buffer, 0, 10);
            outStream.Finish();

            ms.Seek(0, SeekOrigin.Begin);

            var inStream = new ZipInputStream(ms);
            var e = inStream.GetNextEntry();

            MustFailRead(inStream, null, 0, 0);
            MustFailRead(inStream, buffer, -1, 1);
            MustFailRead(inStream, buffer, 0, 11);
            MustFailRead(inStream, buffer, 7, 5);
            MustFailRead(inStream, buffer, 0, -1);

            MustFailRead(inStream, emptyBuffer, 0, 1);

            var bytesRead = inStream.Read(buffer, 10, 0);
            Assert.AreEqual(0, bytesRead, "Should be able to read zero bytes");

            bytesRead = inStream.Read(emptyBuffer, 0, 0);
            Assert.AreEqual(0, bytesRead, "Should be able to read zero bytes");
        }
Ejemplo n.º 10
0
        public void EntryWithNoDataAndZip64()
        {
            MemoryStream msw = new MemoryStreamWithoutSeek();
            var outStream = new ZipOutputStream(msw);

            outStream.IsStreamOwner = false;
            var ze = new ZipEntry("Striped Marlin");
            ze.ForceZip64();
            ze.Size = 0;
            outStream.PutNextEntry(ze);
            outStream.CloseEntry();
            outStream.Finish();
            outStream.Close();

            var ms = new MemoryStream(msw.ToArray());
            using (var zf = new ZipFile(ms))
            {
                Assert.IsTrue(zf.TestArchive(true));
            }
        }
Ejemplo n.º 11
0
        public void EmptyZipEntries()
        {
            var ms = new MemoryStream();
            var outStream = new ZipOutputStream(ms);
            for (var i = 0; i < 10; ++i)
            {
                outStream.PutNextEntry(new ZipEntry(i.ToString()));
            }
            outStream.Finish();

            ms.Seek(0, SeekOrigin.Begin);

            var inStream = new ZipInputStream(ms);

            var extractCount = 0;
            ZipEntry entry;
            var decompressedData = new byte[100];

            while ((entry = inStream.GetNextEntry()) != null)
            {
                while (true)
                {
                    var numRead = inStream.Read(decompressedData, extractCount, decompressedData.Length);
                    if (numRead <= 0)
                    {
                        break;
                    }
                    extractCount += numRead;
                }
            }
            inStream.Close();
            Assert.AreEqual(extractCount, 0, "No data should be read from empty entries");
        }
Ejemplo n.º 12
0
        public void CreateAndReadEmptyZip()
        {
            var ms = new MemoryStream();
            var outStream = new ZipOutputStream(ms);
            outStream.Finish();

            ms.Seek(0, SeekOrigin.Begin);

            var inStream = new ZipInputStream(ms);
            ZipEntry entry;
            while ((entry = inStream.GetNextEntry()) != null)
            {
                Assert.Fail("No entries should be found in empty zip");
            }
        }
Ejemplo n.º 13
0
        public void Stream_UnicodeEntries()
        {
            var ms = new MemoryStream();
            using (var s = new ZipOutputStream(ms))
            {
                s.IsStreamOwner = false;

                var sampleName = "\u03A5\u03d5\u03a3";
                var sample = new ZipEntry(sampleName);
                sample.IsUnicodeText = true;
                s.PutNextEntry(sample);

                s.Finish();
                ms.Seek(0, SeekOrigin.Begin);

                using (var zis = new ZipInputStream(ms))
                {
                    var ze = zis.GetNextEntry();
                    Assert.AreEqual(sampleName, ze.Name, "Expected name to match original");
                    Assert.IsTrue(ze.IsUnicodeText, "Expected IsUnicodeText flag to be set");
                }
            }
        }
Ejemplo n.º 14
0
        public void Stream_64KPlusOneEntries()
        {
            const int target = 65537;
            var ms = new MemoryStream();
            using (var s = new ZipOutputStream(ms))
            {
                for (var i = 0; i < target; ++i)
                {
                    s.PutNextEntry(new ZipEntry("dummyfile.tst"));
                }

                s.Finish();
                ms.Seek(0, SeekOrigin.Begin);
                using (var zipFile = new ZipFile(ms))
                {
                    Assert.AreEqual(target, zipFile.Count, "Incorrect number of entries stored");
                }
            }
        }
Ejemplo n.º 15
0
        internal static void CompressFiles()
        {
            string usedname;

            if (_options.ZipFileName != null)
            {
                usedname = _options.ZipFileName;
            }
            else
            {
                if (_options.RandomFilenames)
                {
                    usedname = Path.GetRandomFileName() + ".zip";
                }
                else
                {
                    usedname = $"{_fileTimeStamp}_BloodHound.zip";
                }
            }
            var zipfilepath = GetZipFileName(usedname);

            Console.WriteLine($"Compressing data to {zipfilepath}.");
            var password = GenerateZipPass();

            if (_options.EncryptZip)
            {
                Console.WriteLine($"Password for zip file is {password}");
                Console.WriteLine("Unzip the files manually to upload to the interface");
            }
            else
            {
                Console.WriteLine("You can upload this file directly to the UI.");
            }

            var buffer = new byte[4096];

            using (var s = new ZipOutputStream(File.Create(zipfilepath)))
            {
                s.SetLevel(9);
                if (_options.EncryptZip)
                {
                    s.Password = password;
                }
                foreach (var file in UsedFiles)
                {
                    var entry = new ZipEntry(Path.GetFileName(file))
                    {
                        DateTime = DateTime.Now
                    };
                    s.PutNextEntry(entry);

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


                    File.Delete(file);
                }

                s.Finish();
                s.Close();
            }

            Console.WriteLine("Finished compressing files!");
        }
Ejemplo n.º 16
0
        public void ZipFiles(string inputFolderPath)
        {
            ArrayList ar         = GenerateFileList(inputFolderPath);
            int       trimLength = (Directory.GetParent(inputFolderPath)).ToString().Length;

            trimLength += 1;
            FileStream ostream;

            byte[] obuffer;

            var oZipStream = new ZipOutputStream(HttpContext.Current.Response.OutputStream);

            oZipStream.SetLevel(6);
            ZipEntry oZipEntry;

            foreach (string file in ar)
            {
                oZipEntry = new ZipEntry(file.Remove(0, trimLength));
                oZipStream.PutNextEntry(oZipEntry);

                if (!file.EndsWith(@"/")) // if a file ends with '/' its a directory
                {
                    ostream = File.OpenRead(file);
                    obuffer = new byte[ostream.Length];
                    ostream.Read(obuffer, 0, obuffer.Length);
                    oZipStream.Write(obuffer, 0, obuffer.Length);
                }
            }

            if (File.Exists(inputFolderPath + "config.xml"))
            {
                var cfg = new ExampleConfig(inputFolderPath + "config.xml", true);
                foreach (string file in cfg.OuterFiles)
                {
                    oZipEntry = new ZipEntry(new FileInfo(file).Name);
                    oZipStream.PutNextEntry(oZipEntry);
                    ostream = File.OpenRead(file);
                    obuffer = new byte[ostream.Length];
                    ostream.Read(obuffer, 0, obuffer.Length);
                    oZipStream.Write(obuffer, 0, obuffer.Length);
                }

                foreach (string folder in cfg.ZipFolders)
                {
                    ar = GenerateFileList(folder);
                    DirectoryInfo dir = new DirectoryInfo(folder);
                    trimLength  = dir.Parent.FullName.Length;
                    trimLength += 1;

                    //oZipEntry = new ZipEntry(dir.Name);
                    //oZipStream.PutNextEntry(oZipEntry);

                    foreach (string file in ar)
                    {
                        oZipEntry = new ZipEntry(file.Remove(0, trimLength));
                        oZipStream.PutNextEntry(oZipEntry);

                        if (!file.EndsWith(@"/")) // if a file ends with '/' its a directory
                        {
                            ostream = File.OpenRead(file);
                            obuffer = new byte[ostream.Length];
                            ostream.Read(obuffer, 0, obuffer.Length);
                            oZipStream.Write(obuffer, 0, obuffer.Length);
                        }
                    }
                }
            }

            oZipStream.Finish();
            oZipStream.Close();
        }
Ejemplo n.º 17
0
 public static void ZipFile(string fileToZip, string zipedFile, int compressionLevel, int blockSize)
 {
     if (!File.Exists(fileToZip))
     {
         throw new FileNotFoundException("指定要压缩的文件: " + fileToZip + " 不存在!");
     }
     using (FileStream stream = File.Create(zipedFile))
     {
         using (ZipOutputStream stream2 = new ZipOutputStream(stream))
         {
             using (FileStream stream3 = new FileStream(fileToZip, FileMode.Open, FileAccess.Read))
             {
                 ZipEntry entry = new ZipEntry(fileToZip.Substring(fileToZip.LastIndexOf(@"\") + 1));
                 stream2.PutNextEntry(entry);
                 stream2.SetLevel(compressionLevel);
                 byte[] buffer = new byte[blockSize];
                 int count = 0;
                 try
                 {
                     do
                     {
                         count = stream3.Read(buffer, 0, buffer.Length);
                         stream2.Write(buffer, 0, count);
                     }
                     while (count > 0);
                 }
                 catch (Exception exception)
                 {
                     throw exception;
                 }
                 stream3.Close();
             }
             stream2.Finish();
             stream2.Close();
         }
         stream.Close();
     }
 }
Ejemplo n.º 18
0
        /// <summary>
        /// Crée une sauvegarge des données de l'utilisateur
        /// </summary>
        public void CreateBackup(string destination)
        {
            Cancel = false;
            // Ferme la connexion à la BD le temps d'effectuer la sauvegarde
            DataBaseFactory.Instance.GetConnection().Close();

            string[] inFiles = Directory.GetFiles(CIV.Common.IO.GetCivDataFolder(), "*", SearchOption.AllDirectories);

            long totalSize = 0;

            foreach (string item in inFiles)
            {
                FileInfo fileInfo = new FileInfo(item);
                totalSize += fileInfo.Length;
            }

            using (FileStream fileStream = new FileStream(destination, FileMode.CreateNew))
            {
                using (ZipOutputStream zipper = new ZipOutputStream(fileStream))
                {
                    zipper.SetLevel(9);
                    zipper.UseZip64 = UseZip64.Off;
                    long totalCurrentRead = 0;

                    for (int i = 0; i < inFiles.Length; i++)
                    {
                        // Enlever le chemin complet
                        ZipEntry entry = new ZipEntry(inFiles[i].Replace(CIV.Common.IO.GetCivDataFolder(), String.Empty));
                        entry.DateTime = DateTime.Now;

                        zipper.PutNextEntry(entry);

                        using (FileStream reader = new FileStream(inFiles[i], FileMode.Open, FileAccess.Read))
                        {
                            byte[] data = new byte[_bufferSize];
                            int    dataRead;
                            long   fileRead = 0;
                            do
                            {
                                dataRead = reader.Read(data, 0, _bufferSize);
                                zipper.Write(data, 0, dataRead);

                                fileRead         += dataRead;
                                totalCurrentRead += dataRead;

                                DoProgress(new BackupProgressEventArgs(100 * totalCurrentRead / totalSize,
                                                                       100 * fileRead / reader.Length,
                                                                       inFiles[i],
                                                                       reader.Length,
                                                                       totalSize,
                                                                       i + 1,
                                                                       inFiles.Length));
                            } while (dataRead > 0 && !Cancel);
                        }
                        if (Cancel)
                        {
                            break;
                        }
                    }
                    zipper.Finish();
                }
            }

            if (Cancel && File.Exists(destination))
            {
                File.Delete(destination);
            }
        }
Ejemplo n.º 19
0
 public static void ZipFile(string fileToZip, string zipedFile)
 {
     if (!File.Exists(fileToZip))
     {
         throw new FileNotFoundException("指定要压缩的文件: " + fileToZip + " 不存在!");
     }
     using (FileStream stream = File.OpenRead(fileToZip))
     {
         byte[] buffer = new byte[stream.Length];
         stream.Read(buffer, 0, buffer.Length);
         stream.Close();
         using (FileStream stream2 = File.Create(zipedFile))
         {
             using (ZipOutputStream stream3 = new ZipOutputStream(stream2))
             {
                 ZipEntry entry = new ZipEntry(fileToZip.Substring(fileToZip.LastIndexOf(@"\") + 1));
                 stream3.PutNextEntry(entry);
                 stream3.SetLevel(5);
                 stream3.Write(buffer, 0, buffer.Length);
                 stream3.Finish();
                 stream3.Close();
             }
         }
     }
 }
Ejemplo n.º 20
0
            /// <summary>
            /// Main method
            /// </summary>
            /// <param name="stZipPath">path of the archive wanted</param>
            /// <param name="stDirToZip">path of the directory we want to create, without ending backslash</param>
            public static void CreateZip(string stZipPath, string stDirToZip)
            {
                try
                {
                //Sanitize inputs
                stDirToZip = Path.GetFullPath(stDirToZip);
                stZipPath = Path.GetFullPath(stZipPath);

                TextLogger2.Log("Zip directory " + stDirToZip);

                //Recursively parse the directory to zip
                Stack<FileInfo> stackFiles = DirExplore(stDirToZip);

                ZipOutputStream zipOutput = null;

                if (File.Exists(stZipPath))
                    File.Delete(stZipPath);

                Crc32 crc = new Crc32();
                zipOutput = new ZipOutputStream(File.Create(stZipPath));
                zipOutput.SetLevel(6); // 0 - store only to 9 - means best compression

                TextLogger2.Log(stackFiles.Count + " files to zip.\n");

                int index = 0;
                foreach (FileInfo fi in stackFiles)
                {
                    ++index;
                    //int percent = (int)((float)index / ((float)stackFiles.Count / 100));
                    //if (percent % 1 == 0)
                    //{
                    //    Console.CursorLeft = 0;
                    //    Console.Write(_stSchon[index % _stSchon.Length].ToString() + " " + percent + "% done.");
                    //}
                    FileStream fs = File.OpenRead(fi.FullName);

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

                    //Create the right arborescence within the archive
                    string stFileName = fi.FullName.Remove(0, stDirToZip.Length + 1);
                    ZipEntry entry = new ZipEntry(stFileName);

                    entry.DateTime = DateTime.Now;

                    // set Size and the crc, because the information
                    // about the size and crc should be stored in the header
                    // if it is not set it is automatically written in the footer.
                    // (in this case size == crc == -1 in the header)
                    // Some ZIP programs have problems with zip files that don't store
                    // the size and crc in the header.
                    entry.Size = fs.Length;
                    fs.Close();

                    crc.Reset();
                    crc.Update(buffer);

                    entry.Crc = crc.Value;

                    zipOutput.PutNextEntry(entry);

                    zipOutput.Write(buffer, 0, buffer.Length);
                }
                zipOutput.Finish();
                zipOutput.Close();
                zipOutput = null;
                }
                catch (Exception)
                {
                throw;
                }
            }
Ejemplo n.º 21
0
        string BuildPackageInternal(IProgressStatus monitor, string targetDirectory, string filePath)
        {
            AddinDescription conf = registry.GetAddinDescription(monitor, filePath);

            if (conf == null)
            {
                monitor.ReportError("Could not read add-in file: " + filePath, null);
                return(null);
            }

            string basePath = Path.GetDirectoryName(filePath);

            if (targetDirectory == null)
            {
                targetDirectory = basePath;
            }

            // Generate the file name

            string name;

            if (conf.LocalId.Length == 0)
            {
                name = Path.GetFileNameWithoutExtension(filePath);
            }
            else
            {
                name = conf.LocalId;
            }
            name = Addin.GetFullId(conf.Namespace, name, conf.Version);
            name = name.Replace(',', '_').Replace(".__", ".");

            string outFilePath = Path.Combine(targetDirectory, name) + ".mpack";

            ZipOutputStream s = new ZipOutputStream(File.Create(outFilePath));

            s.SetLevel(5);

            // Generate a stripped down description of the add-in in a file, since the complete
            // description may be declared as assembly attributes

            XmlDocument doc = new XmlDocument();

            doc.PreserveWhitespace = false;
            doc.LoadXml(conf.SaveToXml().OuterXml);
            CleanDescription(doc.DocumentElement);
            MemoryStream  ms = new MemoryStream();
            XmlTextWriter tw = new XmlTextWriter(ms, System.Text.Encoding.UTF8);

            tw.Formatting = Formatting.Indented;
            doc.WriteTo(tw);
            tw.Flush();
            byte[] data = ms.ToArray();

            var infoEntry = new ZipEntry("addin.info")
            {
                Size = data.Length
            };

            s.PutNextEntry(infoEntry);
            s.Write(data, 0, data.Length);

            // Now add the add-in files

            ArrayList list = new ArrayList();

            if (!conf.AllFiles.Contains(Path.GetFileName(filePath)))
            {
                list.Add(Path.GetFileName(filePath));
            }
            foreach (string f in conf.AllFiles)
            {
                list.Add(f);
            }

            foreach (var prop in conf.Properties)
            {
                try {
                    if (File.Exists(Path.Combine(basePath, prop.Value)))
                    {
                        list.Add(prop.Value);
                    }
                } catch {
                    // Ignore errors
                }
            }

            monitor.Log("Creating package " + Path.GetFileName(outFilePath));

            foreach (string file in list)
            {
                string fp = Path.Combine(basePath, file);
                using (FileStream fs = File.OpenRead(fp)) {
                    byte[] buffer = new byte [fs.Length];
                    fs.Read(buffer, 0, buffer.Length);

                    var entry = new ZipEntry(file)
                    {
                        Size = fs.Length
                    };
                    s.PutNextEntry(entry);
                    s.Write(buffer, 0, buffer.Length);
                }
            }

            s.Finish();
            s.Close();
            return(outFilePath);
        }
Ejemplo n.º 22
0
		/// <summary>
		/// Creates a ZIP archive, returned as a <see cref="ZipOutputStream"/>, containing the specified <paramref name="albumIds">albums
		/// </paramref> and <paramref name="mediaObjectIds">media objects</paramref>. Only media objects associated with a 
		/// physical file are included (in other words, external media objects are excluded). The archive is created in memory
		/// and is not stored on disk.
		/// </summary>
		/// <param name="parentAlbumId">The ID of the album containing the <paramref name="albumIds"/> and <paramref name="mediaObjectIds"/>.
		/// When <paramref name="albumIds"/> or <paramref name="mediaObjectIds"/> belong to more than one album, such as when a user is 
		/// downloading multiple albums contained within a virtual album, specify <see cref="Int32.MinValue"/>.</param>
		/// <param name="albumIds">The ID's of the albums to add to the ZIP archive. It's child albums and media objects are recursively 
		/// added. Each album must exist within the parent album, but does not have to be an immediate child (it can be a grandchild, etc).</param>
		/// <param name="mediaObjectIds">The ID's of the media objects to add to the archive. Each media object must exist within the parent album,
		/// but does not have to be an immediate child (it can be a grandchild, etc).</param>
		/// <param name="imageSize">Size of the image to add to the ZIP archive. This parameter applies only to <see cref="Image"/> 
		/// media objects.</param>
		/// <returns>Returns a <see cref="MemoryStream"/> of a ZIP archive that contains the specified albums and media objects.</returns>
		public Stream CreateZipStream(int parentAlbumId, List<int> albumIds, List<int> mediaObjectIds, DisplayObjectType imageSize)
		{
			string currentItemBasePath;
			string basePath = null;
			bool applyWatermark = true; // Will be overwritten later
			try
			{
				// Get the path to the parent album. This will fail when parentAlbumId does not refer to a valid album.
				basePath = String.Concat(Factory.LoadAlbumInstance(parentAlbumId, false).FullPhysicalPathOnDisk, Path.DirectorySeparatorChar);
				
				applyWatermark = this.DetermineIfWatermarkIsToBeApplied(parentAlbumId);
			}
			catch (ErrorHandler.CustomExceptions.InvalidAlbumException) { /* Ignore for now; we'll check basePath later */ }

			MemoryStream ms = new MemoryStream();
			ZipOutputStream zos = new ZipOutputStream(ms);

			zos.SetLevel(ZIP_COMPRESSION_LEVEL);

			if (albumIds != null)
			{
				foreach (int albumId in albumIds)
				{
					IAlbum album = Factory.LoadAlbumInstance(albumId, true);

					if (String.IsNullOrEmpty(basePath))
					{
						// The base path wasn't assigned because albumParentId does not refer to a valid album. Instead we will use the path
						// of the current album's parent.
						currentItemBasePath = String.Concat(album.Parent.FullPhysicalPathOnDisk, Path.DirectorySeparatorChar);

						applyWatermark = DetermineIfWatermarkIsToBeApplied(albumId);
					}
					else
					{
						currentItemBasePath = basePath;
					}

					AddZipEntry(zos, album, imageSize, currentItemBasePath, applyWatermark);
				}
			}

			if (mediaObjectIds != null)
			{
				foreach (int mediaObjectId in mediaObjectIds)
				{
					IGalleryObject mediaObject = Factory.LoadMediaObjectInstance(mediaObjectId);

					if (String.IsNullOrEmpty(basePath))
					{
						// The base path wasn't assigned because albumParentId does not refer to a valid album. Instead we will use the path
						// of the current media object's album.
						currentItemBasePath = String.Concat(mediaObject.Parent.FullPhysicalPathOnDisk, Path.DirectorySeparatorChar);

						applyWatermark = DetermineIfWatermarkIsToBeApplied(mediaObject.Parent.Id);
					}
					else
					{
						currentItemBasePath = basePath;
					}

					AddFileZipEntry(zos, mediaObject, imageSize, currentItemBasePath, applyWatermark);
				}
			}

			zos.Finish();

			return ms;
		}
Ejemplo n.º 23
0
    private static void GenerateUpdatePackages(BuildAssetConfig assetConfig)
    {
        ResourceConfig oldConfig       = LoadFileFromPackage(assetConfig.packagePath, VERFILE_CONF_PATH);
        ResourceConfig oldUpdateConfig = null;

        if (string.IsNullOrEmpty(assetConfig.updatePackagePath))
        {
            oldUpdateConfig = new ResourceConfig();
        }
        else
        {
            oldUpdateConfig = LoadFileFromPackage(assetConfig.updatePackagePath, UPDATELIST_CONF_PATH);
        }

        // old files md5
        Dictionary <string, string> oldFileMd5 = new Dictionary <string, string>();

        foreach (var item in oldConfig.resource.patchLst)
        {
            oldFileMd5[item.file] = item.md5;
        }
        foreach (var item in oldUpdateConfig.resource.patchLst)
        {
            oldFileMd5[item.file] = item.md5;
        }

        // load new verfile and caculate new verfile md5
        AssetBundle    newVerfileBundle = null;
        ResourceConfig verfileConfig    = new ResourceConfig();
        string         verfileHashValue = string.Empty;

        try
        {
            byte[] verfileBytes = File.ReadAllBytes(Path.Combine(BuildOutputPath, VERFILE_CONF_PATH));
            newVerfileBundle = AssetBundle.LoadFromMemory(verfileBytes);
            string verfileText = newVerfileBundle.LoadAsset <TextAsset>(newVerfileBundle.GetAllAssetNames()[0]).text;
            verfileConfig.Initialize(verfileText);
            ResourceConfig tempVersionJson = new ResourceConfig();
            tempVersionJson.Initialize(verfileText);
            tempVersionJson.resource.patchLst.RemoveAll((item) => { return(item.file.Contains("verfile") || item.file.Contains("updatelist")); });
            verfileHashValue = Utils.HashToMd5(Pathfinding.Serialization.JsonFx.JsonWriter.Serialize(tempVersionJson.resource));
        }
        finally
        {
            if (null != newVerfileBundle)
            {
                newVerfileBundle.Unload(false);
                newVerfileBundle = null;
            }
        }

        ResourceConfig updateConfig = new ResourceConfig();

        updateConfig.resource.hashValue = verfileHashValue;

        ConfResourceItem verfileItem = null;

        foreach (var newItem in verfileConfig.resource.patchLst)
        {
            if (newItem.file.Contains("updatelist"))
            {
                continue;
            }

            if (newItem.file.Contains("verfile"))
            {
                newItem.md5 = Utils.FileToMd5(Path.Combine(BuildOutputPath, VERFILE_CONF_PATH));
                verfileItem = newItem;
                continue;
            }

            var oldItemMd5 = string.Empty;
            oldFileMd5.TryGetValue(newItem.file, out oldItemMd5);
            // add or modify
            if (string.IsNullOrEmpty(oldItemMd5) || oldItemMd5 != newItem.md5)
            {
                updateConfig.resource.patchLst.Add(newItem);
            }
        }

        if (updateConfig.resource.patchLst.Count <= 0)
        {
            updateConfig.resource.hashValue = oldUpdateConfig.resource.hashValue;
        }
        else
        {
            updateConfig.resource.patchLst.Add(verfileItem);
        }

        // set need copy asset map
        Dictionary <string, string> needCopyMap = new Dictionary <string, string>();

        foreach (var item in updateConfig.resource.patchLst)
        {
            needCopyMap.Add(item.file, Path.Combine(BuildOutputPath, item.file));
        }
        needCopyMap[UPDATELIST_CONF_PATH] = Path.Combine(BuildOutputPath, UPDATELIST_CONF_PATH);

        // add old update list to new, but don't need to copy
        foreach (var item in oldUpdateConfig.resource.patchLst)
        {
            // this is the old update list
            if (item.file.Contains("updatelist"))
            {
                continue;
            }

            if (updateConfig.resource.patchLst.FindAll(fileItem => { return(fileItem.file == item.file); }).Count <= 0)
            {
                updateConfig.resource.patchLst.Add(item);
            }
        }

        string updateListConfigText = SerializeJsonFile(updateConfig.resource, UPDATELIST_JSON_PATH);

        string tempDirectory = Path.Combine(Application.dataPath, "../" + FileUtil.GetUniqueTempPathInProject());

        if (!Directory.Exists(tempDirectory))
        {
            Directory.CreateDirectory(tempDirectory);
        }
        AssetBundleBuild[] buildMap = new AssetBundleBuild[]
        {
            new AssetBundleBuild()
            {
                assetBundleName = UPDATELIST_CONF_PATH, assetNames = new string[] { "Assets/data/conf/updatelist.json" }
            },
        };
        BuildPipeline.BuildAssetBundles(tempDirectory, buildMap, BuildAssetBundleOptions.ChunkBasedCompression, CurrentBuildTarget);
        CopyFileEx(Path.Combine(tempDirectory, UPDATELIST_CONF_PATH), Path.Combine(BuildOutputPath, UPDATELIST_CONF_PATH));

        using (MemoryStream compressed = new MemoryStream())
        {
            using (ZipOutputStream compressor = new ZipOutputStream(compressed))
            {
                int count = 0;
                try
                {
                    compressor.SetComment(updateListConfigText);
                }
                catch
                {
                    compressor.SetComment(string.Format("hash:{0}", updateConfig.resource.hashValue));
                }

                foreach (var fileKV in needCopyMap)
                {
                    string   file  = fileKV.Value;
                    ZipEntry entry = new ZipEntry(fileKV.Key);
                    entry.DateTime = new System.DateTime();
                    entry.DosTime  = 0;
                    compressor.PutNextEntry(entry);

                    if (Directory.Exists(file))
                    {
                        continue;
                    }

                    byte[] bytes  = File.ReadAllBytes(file);
                    int    offset = 0;
                    compressor.Write(bytes, offset, bytes.Length - offset);
                    EditorUtility.DisplayProgressBar("Generate update files", string.Format("Add:\t{0}", file), (++count % needCopyMap.Count));
                }

                compressor.Finish();
                compressor.Flush();

                byte[] fileBytes = new byte[compressed.Length];
                Array.Copy(compressed.GetBuffer(), fileBytes, compressed.Length);
                string fileName = string.Format("{0}_{1}_{2}_{3}.zip",
                                                Path.GetFileNameWithoutExtension(assetConfig.packagePath),
                                                DateTime.Now.ToString("yyyy.MM.dd_HH.mm.s"),
                                                Utils.HashToMd5(fileBytes),
                                                updateConfig.resource.hashValue);
                string filePath = Path.Combine(UpdateBuildPath, fileName);
                File.WriteAllBytes(filePath, fileBytes);

                if (null != assetConfig.successCallback)
                {
                    assetConfig.successCallback(filePath);
                }
            }
        }

        EditorUtility.ClearProgressBar();
    }
Ejemplo n.º 24
0
        public string getZipFile(string filedata, string customer)
        {
            string dir     = @"d:/ftpserver/";
            string tmp_dir = @"d:/ftpserver/declare_tmp_zip/";

            if (!Directory.Exists(tmp_dir))
            {
                Directory.CreateDirectory(tmp_dir);
            }
            try
            {
                JArray j_array = JArray.Parse(filedata);

                string codelist = "(";
                int    i        = 0;
                foreach (JObject jo in j_array)
                {
                    codelist += "'" + jo["CODE"] + "'";
                    if (i != j_array.Count - 1)
                    {
                        codelist += ",";
                    }
                    i++;
                }
                codelist += ")";

                string    sql = @"select t.* from list_attachment t where t.filetype='61' and t.declcode in " + codelist + " order by pgindex asc,uploadtime asc";
                DataTable dt  = DBMgr.GetDataTable(sql);


                string filepath = string.Empty;
                //MemoryStream ms = new MemoryStream();
                ZipEntryFactory zipEntryFactory = new ZipEntryFactory();
                //ZipFile zipFile = new ZipFile(ms);
                string filename      = DateTime.Now.ToString("yyyyMMddhhmmssff") + ".zip";
                string newfilename   = string.Empty;
                string sourcefile    = string.Empty;
                string filepath_mask = string.Empty;
                string busitype      = string.Empty;
                using (ZipOutputStream outPutStream = new ZipOutputStream(System.IO.File.Create(tmp_dir + filename)))
                {
                    outPutStream.SetLevel(5);
                    ZipEntry entry  = null;
                    byte[]   buffer = null;
                    //foreach (DataRow dr in dt.Rows)
                    foreach (JObject jo in j_array)
                    {
                        DataRow[] drs = dt.Select("DECLCODE='" + jo["CODE"] + "'");
                        busitype      = jo["BUSITYPE"].ToString();
                        sourcefile    = drs[0]["FILENAME"].ToString();
                        filepath      = dir + sourcefile;
                        filepath_mask = AddBackground(filepath, "企业留存联", busitype, "", customer);
                        newfilename   = jo["DECLARATIONCODE"].ToString() + sourcefile.Substring(sourcefile.LastIndexOf("."));
                        buffer        = new byte[4096];
                        entry         = zipEntryFactory.MakeFileEntry(newfilename);
                        outPutStream.PutNextEntry(entry);
                        using (FileStream fileStream = File.OpenRead(filepath_mask))
                        {
                            StreamUtils.Copy(fileStream, outPutStream, buffer);
                        }
                    }
                    outPutStream.Finish();
                    outPutStream.Close();
                }

                GC.Collect();
                GC.WaitForPendingFinalizers();

                return("/file/declare_tmp_zip/" + filename);
            }
            catch (Exception)
            {
                return("error");
            }
        }
Ejemplo n.º 25
0
        private static Stream GetStreamDocx(Invoice data)
        {
            var invoiceData = InvoiceFormattedData.GetData(data, 0, 0);
            var logo        = new byte[] { };

            if (!string.IsNullOrEmpty(invoiceData.LogoBase64))
            {
                logo = Convert.FromBase64String(invoiceData.LogoBase64);
            }
            else if (invoiceData.LogoBase64Id != 0)
            {
                logo = Convert.FromBase64String(OrganisationLogoManager.GetOrganisationLogoBase64(invoiceData.LogoBase64Id));
            }

            var result = new MemoryStream();

            using (var zipOutputStream = new ZipOutputStream(result))
                using (var zipInputStream = new ZipInputStream(Template))
                {
                    ZipEntry zipEntry;
                    zipOutputStream.IsStreamOwner = false;

                    while ((zipEntry = zipInputStream.GetNextEntry()) != null)
                    {
                        zipOutputStream.PutNextEntry(new ZipEntry(zipEntry.Name));

                        if (zipEntry.Name == DocumentXml)
                        {
                            using (var documentXmlStream = new MemoryStream())
                            {
                                zipInputStream.CopyTo(documentXmlStream);
                                documentXmlStream.Position = 0;

                                var document = new XmlDocument();
                                document.Load(documentXmlStream);
                                var documentStr = GenerateDocumentXml(document, invoiceData, logo);
                                using (var documentStrAsStream = new MemoryStream(Encoding.UTF8.GetBytes(documentStr)))
                                {
                                    documentStrAsStream.CopyTo(zipOutputStream);
                                }
                            }
                            continue;
                        }

                        if (zipEntry.Name == DocumentLogoImage && logo.Length > 0)
                        {
                            using (var logoAsStream = new MemoryStream(logo))
                            {
                                logoAsStream.CopyTo(zipOutputStream);
                            }
                            continue;
                        }

                        zipInputStream.CopyTo(zipOutputStream);
                    }

                    zipOutputStream.Finish();

                    result.Position = 0;
                }

            return(result);
        }
Ejemplo n.º 26
0
        private string CreateResourcePack(LocaleFilePack ResourcePack, string FileName, LanguagePackType packtype)
        {
            int    CompressionLevel = 9;
            int    BlockSize        = 4096;
            string ResPackName;
            string ResPackShortName;

            ResPackShortName = "ResourcePack." + FileName + ".";
            if (packtype == LanguagePackType.Core || packtype == LanguagePackType.Full)
            {
                ResPackShortName += Globals.glbAppVersion + ".";
            }
            ResPackShortName += ResourcePack.LocalePackCulture.Code + ".zip";
            ResPackName       = Globals.HostMapPath + ResPackShortName;

            FileStream strmZipFile = null;

            try
            {
                ProgressLog.AddInfo(string.Format(Localization.GetString("LOG.LangPack.CreateArchive"), ResPackShortName));
                strmZipFile = File.Create(ResPackName);
                ZipOutputStream strmZipStream = null;
                try
                {
                    strmZipStream = new ZipOutputStream(strmZipFile);

                    ZipEntry myZipEntry;
                    myZipEntry = new ZipEntry("Manifest.xml");

                    strmZipStream.PutNextEntry(myZipEntry);
                    strmZipStream.SetLevel(CompressionLevel);

                    byte[] FileData = GetLanguagePackManifest(ResourcePack);

                    strmZipStream.Write(FileData, 0, FileData.Length);
                    ProgressLog.AddInfo(string.Format(Localization.GetString("LOG.LangPack.SavedFile"), "Manifest.xml"));

                    foreach (LocaleFileInfo LocaleFile in ResourcePack.Files)
                    {
                        myZipEntry = new ZipEntry(LocaleFileUtil.GetFullFileName(LocaleFile));
                        strmZipStream.PutNextEntry(myZipEntry);
                        strmZipStream.Write(LocaleFile.Buffer, 0, LocaleFile.Buffer.Length);
                        ProgressLog.AddInfo(string.Format(Localization.GetString("LOG.LangPack.SavedFile"), LocaleFile.LocaleFileName));
                    }
                }
                catch (Exception ex)
                {
                    Exceptions.Exceptions.LogException(ex);
                    ProgressLog.AddFailure(string.Format(Localization.GetString("LOG.LangPack.ERROR.SavingFile"), ex));
                }
                finally
                {
                    if (strmZipStream != null)
                    {
                        strmZipStream.Finish();
                        strmZipStream.Close();
                    }
                }
            }
            catch (Exception ex)
            {
                Exceptions.Exceptions.LogException(ex);
                ProgressLog.AddFailure(string.Format(Localization.GetString("LOG.LangPack.ERROR.SavingFile"), ex));
            }
            finally
            {
                if (strmZipFile != null)
                {
                    strmZipFile.Close();
                }
            }

            return(ResPackName);
        }
Ejemplo n.º 27
0
        public override TaskStatus Run()
        {
            Info("Zipping files...");

            bool success = true;

            var files = SelectFiles();

            if (files.Length > 0)
            {
                var zipPath = Path.Combine(Workflow.WorkflowTempFolder, ZipFileName);

                try
                {
                    using (var s = new ZipOutputStream(File.Create(zipPath)))
                    {
                        s.SetLevel(9); // 0 - store only to 9 - means best compression

                        var buffer = new byte[4096];

                        foreach (FileInf file in files)
                        {
                            // Using GetFileName makes the result compatible with XP
                            // as the resulting path is not absolute.
                            var entry = new ZipEntry(Path.GetFileName(file.Path))
                            {
                                DateTime = DateTime.Now
                            };

                            // Setup the entry data as required.

                            // Crc and size are handled by the library for seakable streams
                            // so no need to do them here.

                            // Could also use the last write time or similar for the file.
                            s.PutNextEntry(entry);

                            using (FileStream fs = File.OpenRead(file.Path))
                            {
                                // Using a fixed size buffer here makes no noticeable difference for output
                                // but keeps a lid on memory usage.
                                int sourceBytes;
                                do
                                {
                                    sourceBytes = fs.Read(buffer, 0, buffer.Length);
                                    s.Write(buffer, 0, sourceBytes);
                                } while (sourceBytes > 0);
                            }
                        }

                        // Finish/Close arent needed strictly as the using statement does this automatically

                        // Finish is important to ensure trailing information for a Zip file is appended.  Without this
                        // the created file would be invalid.
                        s.Finish();

                        // Close is important to wrap things up and unlock the file.
                        s.Close();

                        InfoFormat("Zip {0} created.", zipPath);
                        Files.Add(new FileInf(zipPath, Id));
                    }
                }
                catch (ThreadAbortException)
                {
                    throw;
                }
                catch (Exception e)
                {
                    ErrorFormat("An error occured while creating the Zip {0}", e, zipPath);
                    success = false;
                }
            }

            var status = Status.Success;

            if (!success)
            {
                status = Status.Error;
            }

            Info("Task finished.");
            return(new TaskStatus(status, false));
        }
Ejemplo n.º 28
0
        public static void CreateUpdateInstaller(UpdateDetails updateDetails, string oldArchiveFile, string newArchiveFile, string updateArchiveFile)
        {
            Console.Write("Creating Update install package " + updateArchiveFile + " ");

            //list all files/directories in the old archive
            var oldDirectories = new Dictionary <string, ZipEntry>();
            var oldFiles       = new Dictionary <string, ZipEntry>();

            using (var oldArchive = new ZipFile(oldArchiveFile))
            {
                foreach (ZipEntry entry in oldArchive)
                {
                    if (entry.IsFile)
                    {
                        oldFiles.Add(entry.Name, entry);
                    }
                    else
                    {
                        oldDirectories.Add(entry.Name, entry);
                    }
                }


                //list all files/directories in the new archive
                var newDirectories = new Dictionary <string, ZipEntry>();
                var newFiles       = new Dictionary <string, ZipEntry>();
                using (var newArchive = new ZipFile(newArchiveFile))
                {
                    foreach (ZipEntry entry in newArchive)
                    {
                        if (entry.IsFile)
                        {
                            newFiles.Add(entry.Name, entry);
                        }
                        else
                        {
                            newDirectories.Add(entry.Name, entry);
                        }
                    }

                    //any files in the original archive and not in the new one should be marked for removal.
                    List <string> removeFiles = new List <string>();
                    foreach (var dir in oldDirectories)
                    {
                        if (!newDirectories.ContainsKey(dir.Key))
                        {
                            removeFiles.Add(dir.Key);
                        }
                    }
                    foreach (var file in oldFiles)
                    {
                        if (!newFiles.ContainsKey(file.Key))
                        {
                            removeFiles.Add(file.Key);
                        }
                    }

                    //list all new or newer files/directories in archive2
                    var addDirectories = new Dictionary <string, ZipEntry>();
                    var addFiles       = new Dictionary <string, ZipEntry>();
                    foreach (ZipEntry entry in newArchive)
                    {
                        if (entry.IsFile)
                        {
                            if (!oldFiles.ContainsKey(entry.Name))
                            {
                                addFiles.Add(entry.Name, entry);
                            }
                            else
                            {
                                //do a md5hash of both files to determine if the content is different
                                string oldHash;
                                using (var stream = oldArchive.GetInputStream(oldFiles[entry.Name]))
                                {
                                    oldHash = stream.ComputeMD5();
                                }
                                string newHash;
                                using (var stream = newArchive.GetInputStream(newFiles[entry.Name]))
                                {
                                    newHash = stream.ComputeMD5();
                                }

                                //if the new file has different content, then we want to include it
                                if (oldHash != newHash)
                                {
                                    addFiles.Add(entry.Name, entry);
                                }
                            }
                        }
                        else
                        {
                            addDirectories.Add(entry.Name, entry);
                        }
                    }

                    //write out the files to a new zip archive
                    using (var outputStream = new FileStream(updateArchiveFile, FileMode.Create, FileAccess.Write, FileShare.None))
                    {
                        using (var compressor = new ZipOutputStream(outputStream))
                        {
                            compressor.SetLevel(9);

                            //add new directories
                            foreach (var dir in addDirectories)
                            {
                                compressor.PutNextEntry(new ZipEntry(dir.Value.Name)
                                {
                                    DateTime = dir.Value.DateTime,
                                });
                            }

                            //add new or updated files
                            var data      = new byte[4194304];
                            int milestone = Math.Max(1, addFiles.Count / 10);
                            int i         = 0;
                            foreach (var file in addFiles)
                            {
                                if (i++ % milestone == 0)
                                {
                                    Console.Write('.');
                                }
                                compressor.PutNextEntry(new ZipEntry(file.Value.Name)
                                {
                                    DateTime = file.Value.DateTime,
                                    Size     = file.Value.Size
                                });

                                using (var inputStream = newArchive.GetInputStream(file.Value))
                                {
                                    int bytesRead = inputStream.Read(data, 0, data.Length);
                                    while (bytesRead > 0)
                                    {
                                        compressor.Write(data, 0, bytesRead);
                                        bytesRead = inputStream.Read(data, 0, data.Length);
                                    }
                                }
                            }

                            //add update.json
                            byte[]   updateData  = CreateUpdateFileData(updateDetails, removeFiles);
                            ZipEntry updateEntry = new ZipEntry("update.json")
                            {
                                DateTime = DateTime.UtcNow,
                                Size     = updateData.Length
                            };
                            compressor.PutNextEntry(updateEntry);
                            compressor.Write(updateData, 0, updateData.Length);

                            compressor.Finish();
                        }
                    }
                }
            }
            Console.WriteLine();
        }
Ejemplo n.º 29
0
        /// <summary>
        /// 目录压缩
        /// </summary>
        /// <param name="inputFolderPath">源目录文件</param>
        /// <param name="outputPathAndFile">压缩包路径</param>
        /// <param name="password">压缩包密码</param>
        public static void ZipFolderFiles(string inputFolderPath, string outputPathAndFile, string password)
        {
            ///所有的文件信息
            ArrayList allFiles = GenerateFileList(inputFolderPath);

            ///父目录的长度
            int parentFolderLength = (Directory.GetParent(inputFolderPath)).ToString().Length;

            ///添加 '\\'长度
            parentFolderLength += 2;

            FileStream ostream;

            byte[] obuffer;
            ///压缩包的路径
            string outPath = outputPathAndFile;
            ///创建压缩文件
            ZipOutputStream oZipStream = new ZipOutputStream(File.Create(outPath));

            ///防止文件被不同线程操作
            lock (objLock)
            {
                try
                {
                    ///压缩包密码
                    if (password != null && password != String.Empty)
                    {
                        oZipStream.Password = password;
                    }

                    ///压缩等级
                    oZipStream.SetLevel(9);
                    ZipEntry oZipEntry;

                    ///遍历所有文件,写入压缩包
                    foreach (string file in allFiles)
                    {
                        ///去除父目录得到文件相对路径
                        oZipEntry = new ZipEntry(file.Substring(parentFolderLength));
                        oZipStream.PutNextEntry(oZipEntry);

                        ///文件结构直接写入
                        if (!file.EndsWith(@"/"))
                        {
                            ostream = File.OpenRead(file);
                            obuffer = new byte[ostream.Length];
                            ostream.Read(obuffer, 0, obuffer.Length);
                            oZipStream.Write(obuffer, 0, obuffer.Length);
                            ostream.Close();
                        }
                    }
                }
                catch (Exception ex)
                {
                    X2Error.Log("Zip.ElementFiles", ex, "Zip.ElementFiles");
                    throw ex;
                }
                finally
                {
                    ///数据的释放
                    oZipStream.Finish();
                    oZipStream.Close();
                }
            }
        }
Ejemplo n.º 30
0
        public ActionResult DownloadCompressFiles(string projectGuid, string fileGuidsText, string folderGuidsText, bool isSearchFile = false)
        {
            var dms = GetDMSAndCheckPermission(projectGuid, PermissionType.Read);

            var fileGuids   = string.IsNullOrWhiteSpace(fileGuidsText) ? new List <string>() : CommUtils.Split(fileGuidsText).ToList();
            var folderGuids = string.IsNullOrWhiteSpace(folderGuidsText) ? new List <string>() : CommUtils.Split(folderGuidsText).ToList();

            CommUtils.Assert(fileGuids.Count != 0 || folderGuids.Count != 0, "必须选择一个[文件/文件夹]进行下载");

            //获取待压缩文件夹下的所有文件/文件夹路径
            var dictAllFiles       = new Dictionary <string, string>();
            var allEmptyFolderPath = new List <string>();

            if (folderGuids.Count != 0)
            {
                var folderAndFilePath = new Tuple <List <string>, Dictionary <string, string> >(new List <string>(), new Dictionary <string, string>());
                folderAndFilePath  = GetCompressFilesPath(dms, folderGuids, null, folderAndFilePath);
                dictAllFiles       = folderAndFilePath.Item2;
                allEmptyFolderPath = folderAndFilePath.Item1;
            }

            //获取所有待压缩文件的路径
            var files = new List <DMSFile>();

            foreach (var fileGuid in fileGuids)
            {
                CommUtils.Assert(m_dbAdapter.DMSFile.isExistDMSFile(fileGuid), "找不到文件fileGuid[{0}],请刷新页面后重试", fileGuid);
                var dmsFile   = m_dbAdapter.DMSFile.GetByGuid(fileGuid);
                var projectId = m_dbAdapter.DMSTask.GetProjectIdByDMSId(dms.Instance.Id);
                CommUtils.AssertEquals(dmsFile.DMSId, dms.Instance.Id,
                                       "找不到文件[fileGuid={0}][DMSGuid={1}]", fileGuid, dms.Instance.Guid);

                dictAllFiles[fileGuid] = dmsFile.Name;
                files.Add(dmsFile);
            }

            //处理重名文件
            var keys = dictAllFiles.Keys.ToList();
            var dictResultAllFiles = new Dictionary <string, string>();
            var allFilesPath       = new List <string>();

            foreach (var key in keys)
            {
                dictResultAllFiles[key] = GetNewPathForDupes(dictAllFiles[key], allFilesPath);
                allFilesPath.Add(dictResultAllFiles[key]);
            }

            //压缩-结束
            var resultFilePath     = new List <string>();
            var dictResultFilePath = new Dictionary <string, string>();

            foreach (var fileGuid in dictResultAllFiles.Keys)
            {
                var dmsFile  = m_dbAdapter.DMSFile.GetByGuid(fileGuid);
                var repoFile = Platform.Repository.GetFile(dmsFile.RepoFileId);
                var filePath = repoFile.GetFilePath();

                resultFilePath.Add(filePath);
                dictResultFilePath[filePath] = dictResultAllFiles[fileGuid];
            }

            var             ms        = new MemoryStream();
            ZipOutputStream zipStream = new ZipOutputStream(ms);

            zipStream.SetLevel(3);

            CompressFiles(zipStream, WebConfigUtils.RepositoryFilePath, resultFilePath, dictResultFilePath, allEmptyFolderPath);

            zipStream.Flush();
            zipStream.Finish();

            ms.Seek(0, SeekOrigin.Begin);

            //设置压缩包名称
            var resultZipFileName = string.Empty;

            if (isSearchFile)
            {
                resultZipFileName = "工作文件";
            }
            else
            {
                if (fileGuids.Count == 0 && folderGuids.Count == 1)
                {
                    var currentFolder = dms.FindFolder(folderGuids.First());
                    var currFolder    = currentFolder.Instance;
                    resultZipFileName = currFolder.Name;

                    var fileSeriesList = currentFolder.Files.GroupToDictList(x => x.FileSeries);
                    fileSeriesList.ToList().ForEach(x => {
                        m_dbAdapter.DMSProjectLog.AddDmsProjectLog(projectGuid, x.Key.Guid, "下载[" + x.Key.Name + "]合并于[" + resultZipFileName + ".zip]");
                    });
                }

                if (fileGuids.Count != 0 && folderGuids.Count == 0)
                {
                    var fileSeries     = files.ConvertAll(x => x.DMSFileSeriesId).ToList();
                    var currFileSeries = m_dbAdapter.DMSFileSeries.GetById(files.First().DMSFileSeriesId);
                    if (fileSeries.Distinct().ToList().Count == 1)
                    {
                        resultZipFileName = currFileSeries.Name;
                    }
                    else
                    {
                        var currFolder = m_dbAdapter.DMSFolder.GetById(currFileSeries.DMSFolderId);
                        resultZipFileName = currFolder.ParentFolderId.HasValue ? currFolder.Name : "工作文件";
                    }
                }

                if (string.IsNullOrEmpty(resultZipFileName))
                {
                    var currFolder   = dms.FindFolder(folderGuids.First()).Instance;
                    var parentFolder = m_dbAdapter.DMSFolder.GetById(currFolder.ParentFolderId.Value);

                    resultZipFileName = parentFolder.ParentFolderId.HasValue ? parentFolder.Name : "工作文件";
                }
            }

            //   m_dbAdapter.DMSProjectLog.AddDmsProjectLog(projectGuid, "下载[" + resultZipFileName + ".zip]");
            return(File(ms, "application/octet-stream", resultZipFileName + ".zip"));
        }
Ejemplo n.º 31
0
        string BuildPackageInternal(IProgressStatus monitor, bool debugSymbols, string targetDirectory, string filePath, PackageFormat format)
        {
            AddinDescription conf = registry.GetAddinDescription(monitor, filePath);

            if (conf == null)
            {
                monitor.ReportError("Could not read add-in file: " + filePath, null);
                return(null);
            }

            string basePath = Path.GetDirectoryName(Path.GetFullPath(filePath));

            if (targetDirectory == null)
            {
                targetDirectory = basePath;
            }

            // Generate the file name

            string name;

            if (conf.LocalId.Length == 0)
            {
                name = Path.GetFileNameWithoutExtension(filePath);
            }
            else
            {
                name = conf.LocalId;
            }
            name = Addin.GetFullId(conf.Namespace, name, conf.Version);
            name = name.Replace(',', '_').Replace(".__", ".");

            string outFilePath = Path.Combine(targetDirectory, name);

            switch (format)
            {
            case PackageFormat.Mpack:
                outFilePath += ".mpack";
                break;

            case PackageFormat.Vsix:
                outFilePath += ".vsix";
                break;

            default:
                throw new NotSupportedException(format.ToString());
            }

            ZipOutputStream s = new ZipOutputStream(File.Create(outFilePath));

            s.SetLevel(5);

            if (format == PackageFormat.Vsix)
            {
                XmlDocument doc = new XmlDocument();
                doc.PreserveWhitespace = false;
                doc.LoadXml(conf.SaveToVsixXml().OuterXml);
                MemoryStream  ms = new MemoryStream();
                XmlTextWriter tw = new XmlTextWriter(ms, System.Text.Encoding.UTF8);
                tw.Formatting = Formatting.Indented;
                doc.WriteTo(tw);
                tw.Flush();
                byte [] data = ms.ToArray();

                var infoEntry = new ZipEntry("extension.vsixmanifest")
                {
                    Size = data.Length
                };
                s.PutNextEntry(infoEntry);
                s.Write(data, 0, data.Length);
                s.CloseEntry();
            }

            // Generate a stripped down description of the add-in in a file, since the complete
            // description may be declared as assembly attributes

            if (format == PackageFormat.Mpack || format == PackageFormat.Vsix)
            {
                XmlDocument doc = new XmlDocument();
                doc.PreserveWhitespace = false;
                doc.LoadXml(conf.SaveToXml().OuterXml);
                CleanDescription(doc.DocumentElement);
                MemoryStream  ms = new MemoryStream();
                XmlTextWriter tw = new XmlTextWriter(ms, System.Text.Encoding.UTF8);
                tw.Formatting = Formatting.Indented;
                doc.WriteTo(tw);
                tw.Flush();
                byte [] data = ms.ToArray();

                var infoEntry = new ZipEntry("addin.info")
                {
                    Size = data.Length
                };
                s.PutNextEntry(infoEntry);
                s.Write(data, 0, data.Length);
                s.CloseEntry();
            }

            // Now add the add-in files

            var files = new HashSet <string> ();

            files.Add(Path.GetFileName(Util.NormalizePath(filePath)));

            foreach (string f in conf.AllFiles)
            {
                var file = Util.NormalizePath(f);
                files.Add(file);
                if (debugSymbols)
                {
                    if (File.Exists(Path.ChangeExtension(file, ".pdb")))
                    {
                        files.Add(Path.ChangeExtension(file, ".pdb"));
                    }
                    else if (File.Exists(file + ".mdb"))
                    {
                        files.Add(file + ".mdb");
                    }
                }
            }

            foreach (var prop in conf.Properties)
            {
                try {
                    var file = Util.NormalizePath(prop.Value);
                    if (File.Exists(Path.Combine(basePath, file)))
                    {
                        files.Add(file);
                    }
                } catch {
                    // Ignore errors
                }
            }

            //add satellite assemblies for assemblies in the list
            var satelliteFinder = new SatelliteAssemblyFinder();

            foreach (var f in files.ToList())
            {
                foreach (var satellite in satelliteFinder.FindSatellites(Path.Combine(basePath, f)))
                {
                    var relativeSatellite = satellite.Substring(basePath.Length + 1);
                    files.Add(relativeSatellite);
                }
            }

            monitor.Log("Creating package " + Path.GetFileName(outFilePath));

            foreach (string file in files)
            {
                string fp = Path.Combine(basePath, file);
                using (FileStream fs = File.OpenRead(fp)) {
                    byte[] buffer = new byte [fs.Length];
                    fs.Read(buffer, 0, buffer.Length);

                    var fileName = Path.DirectorySeparatorChar == '\\' ? file.Replace('\\', '/') : file;
                    var entry    = new ZipEntry(fileName)
                    {
                        Size = fs.Length
                    };
                    s.PutNextEntry(entry);
                    s.Write(buffer, 0, buffer.Length);
                    s.CloseEntry();
                }
            }

            if (format == PackageFormat.Vsix)
            {
                files.Add("addin.info");
                files.Add("extension.vsixmanifest");
                XmlDocument doc = new XmlDocument();
                doc.PreserveWhitespace = false;
                XmlDeclaration xmlDeclaration = doc.CreateXmlDeclaration("1.0", "UTF-8", null);
                XmlElement     root           = doc.DocumentElement;
                doc.InsertBefore(xmlDeclaration, root);
                HashSet <string> alreadyAddedExtensions = new HashSet <string> ();
                var typesEl = doc.CreateElement("Types");
                typesEl.SetAttribute("xmlns", "http://schemas.openxmlformats.org/package/2006/content-types");
                foreach (var file in files)
                {
                    var extension = Path.GetExtension(file);
                    if (string.IsNullOrEmpty(extension))
                    {
                        continue;
                    }
                    if (extension.StartsWith(".", StringComparison.Ordinal))
                    {
                        extension = extension.Substring(1);
                    }
                    if (alreadyAddedExtensions.Contains(extension))
                    {
                        continue;
                    }
                    alreadyAddedExtensions.Add(extension);
                    var typeEl = doc.CreateElement("Default");
                    typeEl.SetAttribute("Extension", extension);
                    typeEl.SetAttribute("ContentType", GetContentType(extension));
                    typesEl.AppendChild(typeEl);
                }
                doc.AppendChild(typesEl);
                MemoryStream  ms = new MemoryStream();
                XmlTextWriter tw = new XmlTextWriter(ms, System.Text.Encoding.UTF8);
                tw.Formatting = Formatting.Indented;
                doc.WriteTo(tw);
                tw.Flush();
                byte [] data = ms.ToArray();

                var infoEntry = new ZipEntry("[Content_Types].xml")
                {
                    Size = data.Length
                };
                s.PutNextEntry(infoEntry);
                s.Write(data, 0, data.Length);
                s.CloseEntry();
            }

            s.Finish();
            s.Close();
            return(outFilePath);
        }
Ejemplo n.º 32
0
        /// <summary>
        /// Compactar todos os arquivos do diretorio.
        /// </summary>
        /// <param name="sOrigem">Diretorio de origem</param>
        /// <param name="sDestino">Caminho e nome do arquivo de destino</param>
        /// <returns>True/False para conclusão do processo.</returns>
        public Boolean CompactarDir(String sOrigem, String sDestino)
        {
            try
            {
                if (!Directory.Exists(sOrigem.Substring(0, sOrigem.Length - 1)))
                {
                    Directory.CreateDirectory(sOrigem);
                }

                string[] filenames = Directory.GetFiles(sOrigem);

                // 'using' statements gaurantee the stream is closed properly which is a big source
                // of problems otherwise.  Its exception safe as well which is great.
                using (ZipOutputStream s = new ZipOutputStream(File.Create(sDestino)))
                {
                    s.SetLevel(9); // 0 - store only to 9 - means best compression

                    byte[] buffer = new byte[4096];

                    foreach (string file in filenames)
                    {
                        // Using GetFileName makes the result compatible with XP
                        // as the resulting path is not absolute.
                        ZipEntry entry = new ZipEntry(Path.GetFileName(file));

                        // Setup the entry data as required.

                        // Crc and size are handled by the library for seakable streams
                        // so no need to do them here.

                        // Could also use the last write time or similar for the file.
                        entry.DateTime = DateTime.Now;
                        s.PutNextEntry(entry);

                        using (FileStream fs = File.OpenRead(file))
                        {
                            // Using a fixed size buffer here makes no noticeable difference for output
                            // but keeps a lid on memory usage.
                            int sourceBytes;
                            do
                            {
                                sourceBytes = fs.Read(buffer, 0, buffer.Length);
                                s.Write(buffer, 0, sourceBytes);
                            } while (sourceBytes > 0);
                        }
                    }

                    // Finish/Close arent needed strictly as the using statement does this automatically

                    // Finish is important to ensure trailing information for a Zip file is appended.  Without this
                    // the created file would be invalid.
                    s.Finish();

                    // Close is important to wrap things up and unlock the file.
                    s.Close();
                    return(true);
                }
            }
            catch (Exception ex)
            {
                throw new Exception("Problemas ao gerar arquivo zip.", ex);
            }
        }
Ejemplo n.º 33
0
        public void writeExport(string path)
        {
            try
            {
                FileStream      fs = new FileStream(path, FileMode.Create);
                ZipOutputStream zs = new ZipOutputStream(fs);
                zs.UseZip64 = UseZip64.Off;
                string entry = mData.Settings.Projectname;

                if (mData.Images.Count > 0)
                {
                    ZipEntry ze1 = new ZipEntry("gfx.dat");
                    zs.PutNextEntry(ze1);
                    ZipOutputStream zos = new ZipOutputStream(zs);
                    zos.IsStreamOwner = false;
                    zos.UseZip64      = UseZip64.Off;
                    writeFileRecursive(mMediapool.Nodes[0], mData.Images, zos);
                    zos.Finish();
                    zs.CloseEntry();
                }

                if (mData.Music.Count > 0)
                {
                    ZipEntry ze1 = new ZipEntry("music.dat");
                    zs.PutNextEntry(ze1);
                    ZipOutputStream zos = new ZipOutputStream(zs);
                    zos.IsStreamOwner = false;
                    zos.UseZip64      = UseZip64.Off;
                    writeFileRecursive(mMediapool.Nodes[1], mData.Music, zos);
                    zos.Finish();
                    zs.CloseEntry();
                }

                if (mData.Sounds.Count > 0)
                {
                    ZipEntry ze1 = new ZipEntry("sfx.dat");
                    zs.PutNextEntry(ze1);
                    ZipOutputStream zos = new ZipOutputStream(zs);
                    zos.IsStreamOwner = false;
                    zos.UseZip64      = UseZip64.Off;
                    writeFileRecursive(mMediapool.Nodes[2], mData.Sounds, zos);
                    zos.Finish();
                    zs.CloseEntry();
                }

                if (mData.Videos.Count > 0)
                {
                    ZipEntry ze1 = new ZipEntry("movie.dat");
                    zs.PutNextEntry(ze1);
                    ZipOutputStream zos = new ZipOutputStream(zs);
                    zos.IsStreamOwner = false;
                    zos.UseZip64      = UseZip64.Off;
                    writeFileRecursive(mMediapool.Nodes[3], mData.Videos, zos);
                    zos.Finish();
                    zs.CloseEntry();
                }

                ZipEntry ze5 = new ZipEntry(entry + ".adv");
                zs.PutNextEntry(ze5);
                writeProjectFile(zs, entry, false, false);
                zs.CloseEntry();

                if (mData.Settings.GameIcon.Length > 0)
                {
                    entry = Path.GetFileName(mData.Settings.GameIcon);
                    ZipEntry ze6 = new ZipEntry(entry);
                    zs.PutNextEntry(ze6);
                    writeFile(mData.Settings.GameIcon, zs);
                    zs.CloseEntry();
                }

                zs.Finish();
                fs.Close();
            }
            catch (Exception)
            {
                MessageBox.Show("Failed to write export file " + path + ". Please make sure that it is a writable file.");
            }
        }
Ejemplo n.º 34
0
        /// <summary>
        /// 通过留言信息
        /// </summary>
        /// <returns></returns>
        private Hashtable GetUpdateInfo(HttpContext context)
        {
            Hashtable htRet = new Hashtable();

            try
            {
                string sMode = CConvert.ToString(context.Request["mode"]).Trim();
                if (sMode == "")
                {
                    sMode = "1";//默认【部分更新】
                }

                string sVerCode  = CConvert.ToString(context.Request["vercode"]).Trim();
                string sLastTime = CConvert.ToString(context.Request["lasttime"]).Trim();

                DBIndex dbm = new DBIndex();

                DataSet ds = dbm.getVercodeInfoByCode(sVerCode);
                if (ds.Tables[0].Rows.Count == 0)
                {
                    htRet["ok"]  = false;
                    htRet["msg"] = "授权码错误";
                    return(htRet);
                }


                if (sMode == "2")
                {
                    sLastTime = "2010-01-01 00:00:00";
                }
                //临时文件夹
                string sUpdTime = DateTime.Now.ToString("yyyyMMddHHmmss");
                string sPath    = AppConfig.ImagePath + sVerCode + "/";

                if (Directory.Exists(sPath) == false)
                {
                    Directory.CreateDirectory(sPath);
                }

                DirectoryInfo di = new DirectoryInfo(sPath);
                di.Delete(true);
                if (Directory.Exists(sPath + "anima/") == false)
                {
                    Directory.CreateDirectory(sPath + "anima/");
                }
                if (Directory.Exists(sPath + "train/") == false)
                {
                    Directory.CreateDirectory(sPath + "train/");
                }
                if (Directory.Exists(sPath + "test/") == false)
                {
                    Directory.CreateDirectory(sPath + "test/");
                }
                if (Directory.Exists(sPath + "view/") == false)
                {
                    Directory.CreateDirectory(sPath + "view/");
                }


                //返回的json数据
                Hashtable htJson = new Hashtable();

                //获取最近更新日期之后的 卡通图标
                ArrayList lstAnima = new ArrayList();
                DataSet   dsAnima  = dbm.getAnimaByTime(sLastTime);

                foreach (DataRow dr in dsAnima.Tables[0].Rows)
                {
                    Hashtable ht = new Hashtable();
                    ht["id"]        = CConvert.ToString(dr["img_id"]);
                    ht["file_name"] = CConvert.ToString(dr["file_name"]);

                    File.Copy(AppConfig.ImagePath + "anima/" + CConvert.ToString(dr["file_name"]), sPath + "anima/" + CConvert.ToString(dr["file_name"]));
                    lstAnima.Add(ht);
                }
                htJson["anima"] = lstAnima;

                //课堂训练
                ArrayList lstTrain = new ArrayList();

                DataSet dsTrain = dbm.getTrainByTime("1", sLastTime);
                foreach (DataRow dr in dsTrain.Tables[0].Rows)
                {
                    Hashtable ht = new Hashtable();

                    ht["id"]      = CConvert.ToString(dr["train_id"]);
                    ht["title"]   = CConvert.ToString(dr["title"]);
                    ht["photo"]   = CConvert.ToString(dr["photo"]);
                    ht["content"] = CConvert.ToString(dr["content"]);
                    ht["words"]   = CConvert.ToString(dr["words"]);
                    ht["speed"]   = CConvert.ToString(dr["speed"]);

                    File.Copy(AppConfig.ImagePath + "train/" + CConvert.ToString(dr["photo"]), sPath + "train/" + CConvert.ToString(dr["photo"]));

                    lstTrain.Add(ht);
                }
                htJson["train"] = lstTrain;



                //阅读测评
                ArrayList lstTest = new ArrayList();

                DataSet dsTest = dbm.getTrainByTime("2", sLastTime);
                foreach (DataRow dr in dsTest.Tables[0].Rows)
                {
                    Hashtable ht = new Hashtable();

                    ht["id"]      = CConvert.ToString(dr["train_id"]);
                    ht["title"]   = CConvert.ToString(dr["title"]);
                    ht["photo"]   = CConvert.ToString(dr["photo"]);
                    ht["content"] = CConvert.ToString(dr["content"]);
                    ht["words"]   = CConvert.ToString(dr["words"]);
                    ht["speed"]   = CConvert.ToString(dr["speed"]);
                    File.Copy(AppConfig.ImagePath + "test/" + CConvert.ToString(dr["photo"]), sPath + "test/" + CConvert.ToString(dr["photo"]));

                    lstTest.Add(ht);
                }
                htJson["test"] = lstTest;


                //测评问题
                ArrayList lstQues = new ArrayList();
                DataSet   dsQues  = dbm.getQuesByTime("2", sLastTime);
                foreach (DataRow dr in dsQues.Tables[0].Rows)
                {
                    Hashtable ht = new Hashtable();

                    ht["id"]       = CConvert.ToString(dr["q_id"]);
                    ht["q_type"]   = CConvert.ToString(dr["q_type"]);
                    ht["train_id"] = CConvert.ToString(dr["train_id"]);
                    ht["title"]    = CConvert.ToString(dr["title"]);
                    ht["op1"]      = CConvert.ToString(dr["op1"]);
                    ht["op2"]      = CConvert.ToString(dr["op2"]);
                    ht["op3"]      = CConvert.ToString(dr["op3"]);
                    ht["op4"]      = CConvert.ToString(dr["op4"]);
                    ht["answer"]   = CConvert.ToString(dr["answer"]);

                    lstQues.Add(ht);
                }
                htJson["question"] = lstQues;


                //视幅拓展训练
                ArrayList lstView = new ArrayList();
                DataSet   dsView  = dbm.getViewByTime(sLastTime);
                foreach (DataRow dr in dsView.Tables[0].Rows)
                {
                    Hashtable ht = new Hashtable();

                    ht["id"]      = CConvert.ToString(dr["viewtrain_id"]);
                    ht["type"]    = CConvert.ToString(dr["vt_type"]);
                    ht["title"]   = CConvert.ToString(dr["title"]);
                    ht["photo"]   = CConvert.ToString(dr["photo"]);
                    ht["content"] = CConvert.ToString(dr["content"]);
                    ht["route"]   = CConvert.ToString(dr["route"]);
                    ht["v_desc"]  = CConvert.ToString(dr["v_desc"]);

                    File.Copy(AppConfig.ImagePath + "view/" + CConvert.ToString(dr["photo"]), sPath + "view/" + CConvert.ToString(dr["photo"]));

                    lstView.Add(ht);
                }
                htJson["view"] = lstView;


                JavaScriptSerializer jss = new JavaScriptSerializer();

                StreamWriter sw = new StreamWriter(sPath + "data.json");
                sw.Write(jss.Serialize(htJson));
                sw.Flush();
                sw.Close();

                ZipOutputStream s = new ZipOutputStream(File.Create(AppConfig.ImagePath + sVerCode + sUpdTime + ".zip"));

                s.SetLevel(6);

                Compress(sPath, sPath, s);

                s.Finish();
                s.Close();

                htRet["ok"]       = true;
                htRet["lasttime"] = sUpdTime;
                htRet["file"]     = AppConfig.SiteRoot + "upload/" + sVerCode + sUpdTime + ".zip";


                dbm.InsertUpdateLog(sVerCode);
            }
            catch (Exception ex)
            {
                htRet["ok"]  = false;
                htRet["msg"] = "处理失败!" + ex.Message;
            }
            return(htRet);
        }
Ejemplo n.º 35
0
        void writeFonts(string datadir)
        {
            FileStream      fs      = new FileStream(datadir + "fonts.dat", FileMode.Create);
            ZipOutputStream masterz = new ZipOutputStream(fs);

            masterz.UseZip64 = UseZip64.Off;
            for (int font = 1; font <= mData.Settings.Fonts.Count; ++font)
            {
                Fonts    fnts = new Fonts(mData);
                Bitmap[] images;
                Bitmap[] alphaimages;
                Vec2i    dims;
                Vec2i    numchars;
                int[]    widths = fnts.createBitmapFont(font, out images, out alphaimages, out dims, out numchars);

                string   fontname = String.Format("font.00{0}", font);
                ZipEntry mze      = new ZipEntry(fontname);
                masterz.PutNextEntry(mze);
                ZipOutputStream zos = new ZipOutputStream(masterz);
                zos.UseZip64 = UseZip64.Off;
                for (int i = 0; i < images.Length; ++i)
                {
                    string   imagename = String.Format("font{0}.bm{1}", font, i + 1);
                    ZipEntry ze        = new ZipEntry(imagename);
                    zos.PutNextEntry(ze);
                    MemoryStream ms = new MemoryStream();
                    images[i].Save(ms, ImageFormat.Bmp);
                    zos.Write(ms.GetBuffer(), 0, (int)ms.Length);
                    imagename = String.Format("font{0}.al{1}", font, i + 1);
                    zos.CloseEntry();
                    ze = new ZipEntry(imagename);
                    zos.PutNextEntry(ze);
                    ms = new MemoryStream();
                    alphaimages[i].Save(ms, ImageFormat.Bmp);
                    zos.Write(ms.GetBuffer(), 0, (int)ms.Length);
                    zos.CloseEntry();
                }
                string   dataname = String.Format("fontdata.{0:D3}", font);
                ZipEntry zippe    = new ZipEntry(dataname);
                zos.PutNextEntry(zippe);

                StreamWriter swr = new StreamWriter(zos, Encoding.GetEncoding(1252));
                swr.WriteLine(images.Length);
                swr.WriteLine(dims.x);
                swr.WriteLine(dims.y);
                swr.WriteLine(numchars.x);
                swr.WriteLine(numchars.y);
                foreach (int width in widths)
                {
                    swr.WriteLine(width);
                }
                swr.Flush();
                zos.CloseEntry();
                zos.Finish();

                masterz.CloseEntry();
            }
            masterz.Finish();
            fs.Close();
            //write system font
            System.Reflection.Assembly assy = System.Reflection.Assembly.GetExecutingAssembly();
            Stream fontstr = assy.GetManifestResourceStream("StoryDesigner.Resources.font.dat");
            int    length  = (int)fontstr.Length;

            byte[] fontdat = new byte[length];
            fontstr.Read(fontdat, 0, length);
            fontstr.Close();
            FileStream fontout = new FileStream(datadir + "font.dat", FileMode.Create);

            fontout.Write(fontdat, 0, length);
            fontout.Close();
        }
Ejemplo n.º 36
0
        /// <summary>
        /// 压缩文件夹
        /// </summary>
        /// <param name="sourceList">源文件/文件夹路径列表</param>
        /// <param name="zipFilePath">压缩文件路径</param>
        /// <param name="comment">注释信息</param>
        /// <param name="password">压缩密码</param>
        /// <param name="compressionLevel">压缩等级,范围从0到9,可选,默认为6</param>
        /// <returns></returns>
        public static bool CompressFile(IEnumerable <string> sourceList, string zipFilePath,
                                        string comment = null, string password = null, int compressionLevel = 6)
        {
            bool result = false;

            try
            {
                //检测目标文件所属的文件夹是否存在,如果不存在则建立
                string zipFileDirectory = Path.GetDirectoryName(zipFilePath);
                if (!Directory.Exists(zipFileDirectory))
                {
                    Directory.CreateDirectory(zipFileDirectory);
                }

                var dictionaryList = PrepareFileSystementities(sourceList);

                using (ZipOutputStream zipStream = new ZipOutputStream(File.Create(zipFilePath)))
                {
                    zipStream.Password = password;        //设置密码
                    zipStream.SetComment(comment);        //添加注释
                    zipStream.SetLevel(compressionLevel); //设置压缩等级

                    foreach (var file in dictionaryList)  //从字典取文件添加到压缩文件
                    {
                        if (!file.IsDirectory)            //判断是文件还是文件夹
                        {
                            FileInfo fileItem = new FileInfo(file.Path);
                            using (FileStream readStream = fileItem.Open(FileMode.Open,
                                                                         FileAccess.Read, FileShare.Read))
                            {
                                ZipEntry zipEntry = new ZipEntry(file.Name);
                                zipEntry.DateTime = fileItem.LastWriteTime;
                                zipEntry.Size     = readStream.Length;
                                zipStream.PutNextEntry(zipEntry);
                                int    readLength = 0;
                                byte[] buffer     = new byte[2048];
                                do
                                {
                                    readLength = readStream.Read(buffer, 0, 2048);
                                    zipStream.Write(buffer, 0, readLength);
                                } while (readLength == 2048);

                                readStream.Close();
                            }
                        }
                        else//对文件夹的处理
                        {
                            ZipEntry zipEntry = new ZipEntry(file.Name + "/");
                            zipStream.PutNextEntry(zipEntry);
                        }
                    }

                    zipStream.Flush();
                    zipStream.Finish();
                    zipStream.Close();
                }
                result = true;
            }
            catch (Exception ex)
            {
                throw new Exception("压缩文件失败", ex);
            }
            return(result);
        }
Ejemplo n.º 37
0
        void packGraphics(string datadir)
        {
            FileStream      fs  = new FileStream(datadir + "gfx.dat", FileMode.Create);
            ZipOutputStream zos = new ZipOutputStream(fs);

            zos.UseZip64 = UseZip64.Off;
            if (mData.Settings.ProtectGameFile)
            {
                zos.Password = mZipPwd;
            }

            foreach (KeyValuePair <string, string> entry in mData.Images)
            {
                Bitmap      bmp  = (Bitmap)Bitmap.FromFile(entry.Value);
                string      name = Path.GetFileName(entry.Value);
                ImageFormat fmt  = bmp.RawFormat;
                if (mData.Settings.PngToJpeg && fmt.Equals(ImageFormat.Png))
                {
                    //special handling for pngs
                    Bitmap rgb   = new Bitmap(bmp.Width, bmp.Height);
                    Bitmap alpha = new Bitmap(bmp.Width, bmp.Height);
                    for (int x = 0; x < bmp.Width; ++x)
                    {
                        for (int y = 0; y < bmp.Height; ++y)
                        {
                            Color c = bmp.GetPixel(x, y);
                            rgb.SetPixel(x, y, Color.FromArgb(c.R, c.G, c.B));
                            alpha.SetPixel(x, y, Color.FromArgb(c.A, c.A, c.A));
                        }
                    }
                    string            basename = Path.GetFileNameWithoutExtension(name);
                    EncoderParameters param    = new EncoderParameters(1);
                    param.Param[0] = new EncoderParameter(System.Drawing.Imaging.Encoder.Quality, 100L);
                    ZipEntry ze1 = new ZipEntry(basename + ".pnj");
                    zos.PutNextEntry(ze1);
                    MemoryStream ms = new MemoryStream();
                    rgb.Save(ms, ImageFormat.Jpeg);
                    zos.Write(ms.GetBuffer(), 0, (int)ms.Length);
                    zos.CloseEntry();
                    ZipEntry ze2 = new ZipEntry(basename + ".pna");
                    zos.PutNextEntry(ze2);
                    ms = new MemoryStream();
                    alpha.Save(ms, ImageFormat.Jpeg);
                    zos.Write(ms.GetBuffer(), 0, (int)ms.Length);
                    zos.CloseEntry();
                    bmp.Dispose();
                }
                else
                {
                    bmp.Dispose();
                    ZipEntry ze = new ZipEntry(name);
                    zos.PutNextEntry(ze);
                    //bmp.Save(zos, fmt);
                    writeFile(entry.Value, zos);
                    zos.CloseEntry();
                }
            }

            zos.Finish();
            fs.Close();
        }
Ejemplo n.º 38
0
        /// <summary>
        /// Is an old  method to creates zip from list of zip file  into one.
        /// </summary>
        /// <param name="ZipFileList">List if string of zip name.</param>
        /// <param name="Response">HttpResponse object response</param>
        /// <param name="ZipFileName">Zip file name.</param>
        /// <param name="TempFolder">Folder name containing the zips.</param>
        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;
            }
        }
Ejemplo n.º 39
0
        private void makeZip(string sPath, string sFileName)
        {
            try
            {
                //delete the zip if it's already there.  Just as a safety measure,
                //otherwise it will try to put it in itself.
                File.Delete(sPath + sFileName + ".csk");

                // Depending on the directory this could be very large and would require more attention
                // in a commercial package.
                string[] filenames = Directory.GetFiles(sPath, "*.xml");

                // 'using' statements gaurantee the stream is closed properly which is a big source
                // of problems otherwise.  Its exception safe as well which is great.
                using (ZipOutputStream s = new ZipOutputStream(File.Create(sPath + sFileName + ".csk")))
                {
                    s.SetLevel(9); // 0 - store only to 9 - means best compression

                    byte[] buffer = new byte[4096];

                    foreach (string file in filenames)
                    {
                        // Using GetFileName makes the result compatible with XP
                        // as the resulting path is not absolute.
                        ZipEntry entry = new ZipEntry(Path.GetFileName(file));

                        // Setup the entry data as required.

                        // Crc and size are handled by the library for seakable streams
                        // so no need to do them here.

                        // Could also use the last write time or similar for the file.
                        entry.DateTime = DateTime.Now;
                        s.PutNextEntry(entry);

                        using (FileStream fs = File.OpenRead(file))
                        {
                            // Using a fixed size buffer here makes no noticeable difference for output
                            // but keeps a lid on memory usage.
                            int sourceBytes;
                            do
                            {
                                sourceBytes = fs.Read(buffer, 0, buffer.Length);
                                s.Write(buffer, 0, sourceBytes);
                            } while (sourceBytes > 0);
                        }
                    }

                    // Finish/Close arent needed strictly as the using statement does this automatically

                    // Finish is important to ensure trailing information for a Zip file is appended.  Without this
                    // the created file would be invalid.
                    s.Finish();

                    // Close is important to wrap things up and unlock the file.
                    s.Close();
                }
            }
            catch (Exception ex)
            {
                throw new Exception(ex.Message);
            }
        }
Ejemplo n.º 40
0
    public static void TestZipped()
    {
      DateTime t1, t2;
      TimeSpan dt;

      Foo o = new Foo();
      o.Fill(100000);

      t1 = DateTime.Now;
      XmlDocumentSerializationInfo info = new XmlDocumentSerializationInfo();
      info.AddValue("FooNode",o);

      System.IO.FileStream zipoutfile = System.IO.File.Create(@"C:\temp\xmltest03.xml.zip");
      ZipOutputStream ZipStream = new ZipOutputStream(zipoutfile);
      ZipEntry ZipEntry = new ZipEntry("Table/Table1.xml");
      ZipStream.PutNextEntry(ZipEntry);
      ZipStream.SetLevel(7);
      info.Doc.Save(ZipStream);
      ZipStream.Finish();
      ZipStream.Close();
      zipoutfile.Close();

      t2 = DateTime.Now;
      dt = t2-t1;
      Console.WriteLine("Document saved, duration {0}.",dt);

      t1 = DateTime.Now;
      ZipFile zipfile = new ZipFile(@"C:\temp\xmltest03.xml.zip");
      System.IO.Stream zipinpstream = zipfile.GetInputStream(new ZipEntry("Table/Table1.xml"));
      XmlDocument doc3 = new XmlDocument();
      doc3.Load(zipinpstream);
      XmlDocumentSerializationInfo info3 = new XmlDocumentSerializationInfo(doc3);
      Foo o3 = (Foo)info3.GetValue(null);
      zipinpstream.Close();
      zipfile.Close();
      t2 = DateTime.Now;
      dt = t2-t1;

      Console.WriteLine("Document restored, duration {0}.",dt);
    }
Ejemplo n.º 41
0
        /// <summary>
        /// Creates a ZIP archive, returned as a <see cref="Stream" />, containing the specified <paramref name="albumIds">albums
        /// </paramref> and <paramref name="mediaObjectIds">media objects</paramref>. Only media objects associated with a
        /// physical file are included (in other words, external media objects are excluded). When <paramref name="filePath" /> is specified,
        /// the returned stream is a <see cref="FileStream" />; otherwise a <see cref="MemoryStream" /> is returned.
        /// </summary>
        /// <param name="parentAlbumId">The ID of the album containing the <paramref name="albumIds" /> and <paramref name="mediaObjectIds" />.
        /// When <paramref name="albumIds" /> or <paramref name="mediaObjectIds" /> belong to more than one album, such as when a user is
        /// downloading multiple albums within a virtual album, specify the root album ID (preferably) or <see cref="Int32.MinValue" />.
        /// (If <see cref="Int32.MinValue" /> is specified, items in the ZIP file will be at a single level when they belong to multiple albums.)</param>
        /// <param name="albumIds">The ID's of the albums to add to the ZIP archive. It's child albums and media objects are recursively
        /// added. Each album must exist within the parent album, but does not have to be an immediate child (it can be a grandchild, etc).</param>
        /// <param name="mediaObjectIds">The ID's of the media objects to add to the archive. Each media object must exist within the parent album,
        /// but does not have to be an immediate child (it can be a grandchild, etc).</param>
        /// <param name="imageSize">Size of the image to add to the ZIP archive. This parameter applies only to <see cref="Image" />
        /// media objects.</param>
        /// <param name="filePath">The full file path to a location on the server where the ZIP archive is to be saved. When omitted, a
        /// <see cref="MemoryStream" /> is returned.</param>
        /// <returns>Returns a <see cref="MemoryStream" /> or, if <paramref name="filePath" /> is specified, a <see cref="FileStream" />
        /// of a ZIP archive that contains the specified albums and media objects.</returns>
        public Stream CreateZipStream(int parentAlbumId, IEnumerable <int> albumIds, IEnumerable <int> mediaObjectIds, DisplayObjectType imageSize, string filePath = null)
        {
            string currentItemBasePath;
            string basePath = null;

            try
            {
                // Get the path to the parent album. This will fail when parentAlbumId does not refer to a valid album.
                IAlbum album = Factory.LoadAlbumInstance(parentAlbumId);

                basePath = String.Concat(album.FullPhysicalPathOnDisk, Path.DirectorySeparatorChar);
            }
            catch (Events.CustomExceptions.InvalidAlbumException) { /* Ignore for now; we'll check basePath later */ }

            var ms = string.IsNullOrEmpty(filePath) ? (Stream) new MemoryStream() : new FileStream(filePath, FileMode.Create);

            ZipOutputStream zos = new ZipOutputStream(ms);

            zos.SetLevel(ZIP_COMPRESSION_LEVEL);

            if (albumIds != null)
            {
                foreach (int albumId in albumIds)
                {
                    IAlbum album;
                    try
                    {
                        album = Factory.LoadAlbumInstance(new AlbumLoadOptions(albumId)
                        {
                            InflateChildObjects = true
                        });
                    }
                    catch (Events.CustomExceptions.InvalidAlbumException ex)
                    {
                        Events.EventController.RecordError(ex, AppSetting.Instance);
                        continue; // Gallery object may have been deleted by someone else, so just skip it.
                    }

                    if (String.IsNullOrEmpty(basePath))
                    {
                        // The base path wasn't assigned because albumParentId does not refer to a valid album. Instead we will use the path
                        // of the current album's parent.
                        if (album.Parent is NullObjects.NullGalleryObject)
                        {
                            currentItemBasePath = string.Concat(album.FullPhysicalPathOnDisk, Path.DirectorySeparatorChar);
                        }
                        else
                        {
                            currentItemBasePath = string.Concat(album.Parent.FullPhysicalPathOnDisk, Path.DirectorySeparatorChar);
                        }
                    }
                    else
                    {
                        currentItemBasePath = basePath;
                    }

                    AddZipEntry(zos, album, imageSize, currentItemBasePath, DetermineIfWatermarkIsToBeApplied(album));
                }
            }

            if (mediaObjectIds != null)
            {
                foreach (int mediaObjectId in mediaObjectIds)
                {
                    IGalleryObject mediaObject;
                    try
                    {
                        mediaObject = Factory.LoadMediaObjectInstance(mediaObjectId);
                    }
                    catch (ArgumentException ex)
                    {
                        Events.EventController.RecordError(ex, AppSetting.Instance);
                        continue; // Gallery object may have been deleted by someone else, so just skip it.
                    }
                    catch (InvalidMediaObjectException ex)
                    {
                        Events.EventController.RecordError(ex, AppSetting.Instance);
                        continue; // Gallery object may have been deleted by someone else, so just skip it.
                    }

                    if (String.IsNullOrEmpty(basePath))
                    {
                        // The base path wasn't assigned because albumParentId does not refer to a valid album. Instead we will use the path
                        // of the current media object's album.
                        currentItemBasePath = String.Concat(mediaObject.Parent.FullPhysicalPathOnDisk, Path.DirectorySeparatorChar);
                    }
                    else
                    {
                        currentItemBasePath = basePath;
                    }

                    AddFileZipEntry(zos, mediaObject, imageSize, currentItemBasePath, DetermineIfWatermarkIsToBeApplied((IAlbum)mediaObject.Parent));
                }
            }

            zos.Finish();

            return(ms);
        }
Ejemplo n.º 42
0
        /// <summary>
        /// ZIP:压缩单个文件
        /// add yuangang by 2016-06-13
        /// </summary>
        /// <param name="FileToZip">需要压缩的文件(绝对路径)</param>
        /// <param name="ZipedPathFileName">压缩后的文件名称(绝对路径)</param>
        /// <param name="CompressionLevel">压缩等级(0 无 - 9 最高,默认 5)</param>
        /// <param name="BlockSize">缓存大小(每次写入文件大小,默认 2048)</param>
        /// <param name="IsEncrypt">是否加密(默认 加密)</param>
        public static bool ZipFile(string FileToZip, string ZipedPathFileName, ref string errInfo, int CompressionLevel = 8, int BlockSize = 2048, bool IsEncrypt = false)
        {
            //如果文件没有找到,则报错
            if (!System.IO.File.Exists(FileToZip))
            {
                errInfo = string.Format("源文件不存在!");
                return(false);
            }

            //文件名称(默认同源文件名称相同)
            string ZipFileName = ZipedPathFileName;

            using (System.IO.FileStream ZipFile = System.IO.File.Create(ZipFileName))
            {
                using (ZipOutputStream ZipStream = new ZipOutputStream(ZipFile))
                {
                    using (System.IO.FileStream StreamToZip = new System.IO.FileStream(FileToZip, System.IO.FileMode.Open, System.IO.FileAccess.Read))
                    {
                        string fileName = FileToZip.Substring(FileToZip.LastIndexOf("\\") + 1);

                        ZipEntry ZipEntry = new ZipEntry(fileName);

                        if (IsEncrypt)
                        {
                            //压缩文件加密
                            ZipStream.Password = "******";
                        }

                        ZipStream.PutNextEntry(ZipEntry);

                        //设置压缩级别
                        ZipStream.SetLevel(CompressionLevel);

                        //缓存大小
                        byte[] buffer   = new byte[BlockSize];
                        int    sizeRead = 0;

                        try
                        {
                            do
                            {
                                sizeRead = StreamToZip.Read(buffer, 0, buffer.Length);
                                ZipStream.Write(buffer, 0, sizeRead);
                            }while (sizeRead > 0);
                        }
                        catch (System.Exception ex)
                        {
                            errInfo = ex.Message;
                            return(false);
                        }

                        StreamToZip.Close();
                    }

                    ZipStream.Finish();
                    ZipStream.Close();
                }

                ZipFile.Close();
            }

            return(true);
        }
Ejemplo n.º 43
0
        /// <summary>
        /// Create a new zip file
        /// </summary>
        /// <param name="zipName"></param>
        /// <param name="backDirName"></param>
        /// <param name="daysToKeep"></param>
        /// <param name="fileExt"></param>
        /// <returns></returns>
        private static bool CreateZipFile(string zipName, string backDirName, int daysToKeep, string fileExt)
        {
            try
            {
                // Depending on the directory this could be very large and would require more attention
                string[] filenames = Directory.GetFiles(backDirName);

                // 'using' statements guarantee the stream is closed properly which is a big source
                // of problems otherwise.  Its exception safe as well which is great.
                using (ZipOutputStream zipStream = new ZipOutputStream(File.Create(zipName)))
                {
                    // 0 - store only to 9 - means best compression
                    zipStream.SetLevel(9);

                    // To unpacked by built-in extractor, Specify UseZip64.Off, or set the Size.
                    zipStream.UseZip64 = UseZip64.Dynamic;

                    byte[] buffer = new byte[4096];                     // maximum of file size to read 4GB

                    foreach (string file in filenames)
                    {
                        FileInfo archiFI = new FileInfo(file);

                        if (archiFI.Extension == fileExt)
                        {
                            DateTime dtThen = new DateTime(archiFI.LastWriteTime.Ticks);

                            if (DateTime.Now.Subtract(dtThen).Days >= daysToKeep)
                            {
                                // Using GetFileName as the resulting path is not absolute.
                                ZipEntry entry = new ZipEntry(Path.GetFileName(file))
                                {
                                    DateTime = dtThen
                                };
                                zipStream.PutNextEntry(entry);

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

                                archiFI.Delete();

                                cntArcFiles += 1;

                                Console.Write(".");
                                sbLog.AppendFormat("\r\nAdding ==> {0} - {1}", archiFI.Name, DateTime.Now.TimeOfDay);
                            }
                        }
                    }
                    // Finish is important without this the created file would be invalid.
                    zipStream.Finish();
                    // Close is important to wrap things up and unlock the file.
                    zipStream.Close();
                }                 // end Using

                // if cntArcFiles = 0 then delete the zip file cause it' empty.
                if (cntArcFiles == 0)
                {
                    FileInfo archiFI = new FileInfo(zipName);
                    archiFI.Delete();
                }

                return(true);
            }
            catch (Exception ex)
            {
                sbLog.AppendFormat("\r\n\r\nERROR: {0}", ex);
                return(false);
            }
        }
Ejemplo n.º 44
0
        void NewCompress(string sZipFileFullPathName,SPList sList)
        {
            SPSecurity.RunWithElevatedPrivileges(delegate
            {
                ZipOutputStream zs = new ZipOutputStream(File.Create(sZipFileFullPathName));//D:/project/Dowload/DownLoadFile/1-2-3.zip
                zs.SetLevel(0);

                foreach (string sId in sIDS.Split('-'))
                {
                    SPListItem item = sList.GetItemById(int.Parse(sId));
                    iParentFolderLength=item.Url.LastIndexOf('/')+1;
                    NewCreateZip(item, zs);
                }
                zs.Finish();
                zs.Close();
                GC.Collect();
            });
        }
Ejemplo n.º 45
0
        /// <summary>
        /// 壓縮文件返回壓縮檔名稱
        /// </summary>
        /// <returns>string 返回壓縮后的zip文件名稱</returns>
        public string CompressReturnFileName()
        {
            //if (this.ZipParameter.Zip_Name == "")
            //    ZipParameter.Zip_Name = "ZipFile" + Guid.NewGuid().ToString();

            //zipOper = ZipFile.Create(ZipParameter.Zip_Name);

            //zipOper.BeginUpdate();

            //if (ZipParameter.File != "")
            //    zipOper.Add(ZipParameter.File);

            //foreach (string filename in ZipParameter.FileList)
            //    zipOper.Add(filename);

            //zipOper.CommitUpdate();

            //if (ZipParameter.DirectoryName != "")
            //{
            //    fastzipOper = new FastZip();
            //    if (Directory.Exists(ZipParameter.DirectoryName))
            //        fastzipOper.CreateZip(ZipParameter.Zip_Name, ZipParameter.DirectoryName, true, "");
            //    else
            //        throw new DirectoryNotFoundException("找不到指定的壓縮目錄!");
            //}
            try
            {
                var path = Path.GetDirectoryName(ZipParameter.Zip_Name);
                if (!Directory.Exists(path))
                {
                    Directory.CreateDirectory(path);
                }

                Zip_File           = File.Create(ZipParameter.Zip_Name);
                ZipStream          = new ZipOutputStream(Zip_File);
                ZipStream.Password = ZipParameter.Password;
                ZipStream.SetLevel(ZipParameter.Level);
                foreach (string FileToZip in ZipParameter.FileList)
                {
                    Zip_File = File.OpenRead(FileToZip);
                    byte[] buffer = new byte[Zip_File.Length];
                    Zip_File.Read(buffer, 0, buffer.Length);
                    Zip_File.Close();
                    ZipEntry = new ZipEntry(Path.GetFileName(FileToZip));
                    ZipStream.PutNextEntry(ZipEntry);
                    ZipStream.Write(buffer, 0, buffer.Length);
                }
            }
            finally
            {
                if (ZipEntry != null)
                {
                    ZipEntry = null;
                }
                if (ZipStream != null)
                {
                    ZipStream.Finish();
                    ZipStream.Close();
                }
                if (Zip_File != null)
                {
                    Zip_File.Close();
                    Zip_File = null;
                }
                GC.Collect();
                GC.Collect(1);
            }


            return(ZipParameter.Zip_Name);
        }
Ejemplo n.º 46
0
		/// <summary>
		/// Creates a ZIP archive, returned as a <see cref="ZipOutputStream"/>, containing the specified <paramref name="filePath"/>.
		/// The archive is created in memory and is not stored on disk. If filePath is an image, no attempt is made to apply a
		/// watermark, even if watermarking is enabled.
		/// </summary>
		/// <param name="filePath">The full path to a file to be added to a ZIP archive.</param>
		/// <returns>Returns a <see cref="MemoryStream"/> of a ZIP archive that contains the specified file.</returns>
		public Stream CreateZipStream(string filePath)
		{
			MemoryStream ms = new MemoryStream();
			ZipOutputStream zos = new ZipOutputStream(ms);

			zos.SetLevel(ZIP_COMPRESSION_LEVEL);

			AddFileZipEntry(zos, filePath, null, Path.GetDirectoryName(filePath), false, false);

			zos.Finish();

			return ms;
		}
            public static IFile New(IFile wrapFile, string name, string version, params string[] descriptorLines)
            {
                //var wrapFile = new InMemoryFile(name + "-" + version + ".wrap");
                using (var wrapStream = wrapFile.OpenWrite())
                using (var zipFile = new ZipOutputStream(wrapStream))
                {
                    var nameTransform = new ZipNameTransform();

                    zipFile.PutNextEntry(new ZipEntry(name + ".wrapdesc"));

                    var descriptorContent = descriptorLines.Any()
                                                    ? string.Join("\r\n", descriptorLines)
                                                    : " ";

                    zipFile.Write(Encoding.UTF8.GetBytes(descriptorContent));

                    var versionEntry = new ZipEntry("version");
                    zipFile.PutNextEntry(versionEntry);

                    var versionData = Encoding.UTF8.GetBytes(version);
                    zipFile.Write(versionData);
                    zipFile.Finish();
                }
                return wrapFile;
            }