Ejemplo n.º 1
0
        private void ZipOneFile(string sourceFilePath, string entryName, string zipFilePath)
        {
            ZipFile?zipFile = null;

            try
            {
                zipFile = new ZipFile(File.Open(zipFilePath, FileMode.OpenOrCreate));
                zipFile.BeginUpdate();

                if (zipFile.FindEntry(entryName, false) < 0)
                {
                    zipFile.Add(sourceFilePath, entryName);
                }

                zipFile.CommitUpdate();
            }
            catch (Exception e)
            {
                this.EventLogger.LogEvent($"Failed to Zip the File {sourceFilePath}. Error {e.Message}");
                zipFile?.AbortUpdate();
            }
            finally
            {
                zipFile?.Close();
            }
        }
Ejemplo n.º 2
0
        public static void PackageFiles(string fullFileName, IEnumerable <string> fileNames)
        {
            FileInfo file   = new FileInfo(fullFileName);
            Stream   stream = null;

            if (!file.Directory.Exists)
            {
                file.Directory.Create();
            }
            if (!file.Exists)
            {
                stream = file.Create();
            }
            else
            {
                stream = file.Open(FileMode.OpenOrCreate, FileAccess.ReadWrite);
            }
            ZipFile zip = new ZipFile(stream);

            try
            {
                zip.BeginUpdate();
                foreach (var key in fileNames)
                {
                    FileInfo f = new FileInfo(key);
                    zip.Add(key, f.Name);
                }
                zip.CommitUpdate();
            }
            finally
            {
                stream?.Close();
                zip?.Close();
            }
        }
        private void RegisterImageFromFile(string fullFileName)
        {
            var fileExists = File.Exists(fullFileName);

            if (fileExists)
            {
                // Perhaps use this instead???? https://github.com/icsharpcode/SharpZipLib/wiki/Unpack-a-zip-using-ZipInputStream
                if (fullFileName.EndsWith(".zip", StringComparison.OrdinalIgnoreCase))
                {
                    var zf = new ZipFile(fullFileName);
                    try
                    {
                        foreach (var entry in zf)
                        {
                            if (entry is ZipEntry zipEntry)
                            {
                                if (zipEntry.IsFile && zipEntry.Name.EndsWith(".png", StringComparison.OrdinalIgnoreCase))
                                {
                                    var source = new ZipFileTranslatedImageSource(zf, zipEntry);
                                    RegisterImageFromStream(fullFileName + Path.DirectorySeparatorChar + zipEntry.Name, source);
                                }
                            }
                        }
                    }
                    finally
                    {
                        if (Settings.CacheTexturesInMemory)
                        {
                            zf.Close();
                        }
                    }
                }
                else
                {
                    var source = new FileSystemTranslatedImageSource(fullFileName);
                    RegisterImageFromStream(fullFileName, source);
                }
            }
        }
Ejemplo n.º 4
0
        /// <summary>
        /// Create a QueryResult from a serialized result.
        /// </summary>
        /// <param name="queryResultFile">The file that contains a serialized query result</param>
        /// <returns></returns>
        public static CompressedMetadataStore Open(string queryResultFile)
        {
            var resultArchive = new ZipFile(queryResultFile);

            var indexEntry = resultArchive.GetEntry(IndexFileName);

            try
            {
                if (indexEntry == null)
                {
                    throw new Exception("Index missing from metadata source file");
                }

                using (var indexStream = resultArchive.GetInputStream(indexEntry))
                {
                    using (var indexStreamReader = new StreamReader(indexStream))
                    {
                        var deserializedResult = JsonConvert.DeserializeObject <CompressedMetadataStore>(indexStreamReader.ReadToEnd());
                        if (deserializedResult.Version != CurrentVersion)
                        {
                            throw new Exception("Invalid version");
                        }

                        deserializedResult.FilePath = queryResultFile;

                        deserializedResult.OnDeserialized();

                        deserializedResult.InputFile = resultArchive;

                        return(deserializedResult);
                    }
                }
            }
            catch (Exception ex)
            {
                resultArchive.Close();
                throw ex;
            }
        }
Ejemplo n.º 5
0
        public void PartialStreamClosing()
        {
            string tempFile = GetTempFilePath();

            Assert.IsNotNull(tempFile, "No permission to execute this test?");

            if (tempFile != null)
            {
                tempFile = Path.Combine(tempFile, "SharpZipTest.Zip");
                MakeZipFile(tempFile, new String[] { "Farriera", "Champagne", "Urban myth" }, 10, "Aha");

                using (ZipFile zipFile = new ZipFile(tempFile))
                {
                    Stream stream = zipFile.GetInputStream(0);
                    stream.Close();

                    stream = zipFile.GetInputStream(1);
                    zipFile.Close();
                }
                File.Delete(tempFile);
            }
        }
Ejemplo n.º 6
0
        void ExtractSupportFiles(string targetDir, string file, AddinInfo ainfo)
        {
            Random  r     = new Random();
            ZipFile zfile = new ZipFile(file);

            try {
                foreach (var prop in ainfo.Properties)
                {
                    ZipEntry ze = zfile.GetEntry(prop.Value);
                    if (ze != null)
                    {
                        string fname;
                        do
                        {
                            fname = Path.Combine(targetDir, r.Next().ToString("x") + Path.GetExtension(prop.Value));
                        } while (File.Exists(fname));

                        if (!Directory.Exists(targetDir))
                        {
                            Directory.CreateDirectory(targetDir);
                        }

                        using (var f = File.OpenWrite(fname)) {
                            using (Stream s = zfile.GetInputStream(ze)) {
                                byte [] buffer = new byte [8092];
                                int     nr     = 0;
                                while ((nr = s.Read(buffer, 0, buffer.Length)) > 0)
                                {
                                    f.Write(buffer, 0, nr);
                                }
                            }
                        }
                        prop.Value = Path.Combine(addinFilesDir, Path.GetFileName(fname));
                    }
                }
            } finally {
                zfile.Close();
            }
        }
Ejemplo n.º 7
0
        private void CompressAddOn(string zipPath, List <string> filesForZip, string addOnFolder)
        {
            try {
                ZipFile z = ZipFile.Create(zipPath);
                z.BeginUpdate();


                foreach (string fileName in filesForZip)
                {
                    Console.WriteLine("     {0}", fileName);
                    z.Add(fileName, fileName.Replace(addOnFolder, ""));
                }
                Console.WriteLine("Zipping...");

                z.CommitUpdate();
                z.Close();
                Console.WriteLine("Compressing done");
            }
            catch (Exception e) {
                Console.WriteLine(e.Message);
            }
        }
Ejemplo n.º 8
0
        private bool ExtractZip(string archive, SPath outFolder, CancellationToken cancellationToken,
                                Action <string, long> onStart, Func <long, long, string, bool> onProgress, Func <string, bool> onFilter = null)
        {
            ZipFile zf = null;

            try
            {
                var fs = SPath.FileSystem.OpenRead(archive);
                zf = new ZipFile(fs);
                List <IArchiveEntry> entries = PreprocessEntries(outFolder, zf, onStart, onFilter);
                return(ExtractArchive(archive, outFolder, cancellationToken, zf, entries, onStart, onProgress, onFilter));
            }
            catch (Exception ex)
            {
                LogHelper.GetLogger <ZipHelper>().Error(ex);
                throw;
            }
            finally
            {
                zf?.Close();                 // Ensure we release resources
            }
        }
Ejemplo n.º 9
0
        public static void Uncompress() //This is actually the whole process MadCow uses after Downloading source.
        {
            ZipFile zip    = null;
            var     events = new FastZipEvents();

            FastZip z      = new FastZip(events);
            var     stream = new FileStream(Path.GetTempPath() + @"\MadCow.zip", FileMode.Open, FileAccess.Read);

            zip = new ZipFile(stream);
            zip.IsStreamOwner = true; //Closes parent stream when ZipFile.Close is called
            zip.Close();

            Task task = Task.Factory.StartNew(() => z.ExtractZip(Path.GetTempPath() + @"\MadCow.zip", Path.GetTempPath() + @"\" + @"MadCow\", null));

            task.Wait();

            Form1.GlobalAccess.Invoke(new Action(() =>
            {
                Form1.GlobalAccess.UncompressSuccessDot.Visible = true;
                Form1.GlobalAccess.UncompressingLabel.ForeColor = System.Drawing.Color.Green;
            }));
        }
Ejemplo n.º 10
0
 public InstallableAddIn(string fileName, bool isPackage)
 {
     this.fileName  = fileName;
     this.isPackage = isPackage;
     if (isPackage)
     {
         ZipFile file = new ZipFile(fileName);
         try {
             LoadAddInFromZip(file);
         } finally {
             file.Close();
         }
     }
     else
     {
         addIn = AddIn.Load(fileName);
     }
     if (addIn.Manifest.PrimaryIdentity == null)
     {
         throw new AddInLoadException(ResourceService.GetString("AddInManager.AddInMustHaveIdentity"));
     }
 }
Ejemplo n.º 11
0
 public InstallableAddIn(string fileName, bool isPackage)
 {
     this.fileName  = fileName;
     this.isPackage = isPackage;
     if (isPackage)
     {
         ZipFile file = new ZipFile(fileName);
         try {
             LoadAddInFromZip(file);
         } finally {
             file.Close();
         }
     }
     else
     {
         addIn = AddIn.Load(fileName);
     }
     if (addIn.Manifest.PrimaryIdentity == null)
     {
         throw new AddInLoadException("The AddIn must have an <Identity> for use with the AddIn-Manager.");
     }
 }
Ejemplo n.º 12
0
        internal static String GetZipContentListString(String fileNameAndPath)
        {
            ZipFile zipFile = null;
            String  listString;

            try
            {
                zipFile    = new ZipFile(fileNameAndPath);
                listString = String.Empty;

                for (int i = 0; i < zipFile.Count; i++)
                {
                    ZipEntry zipEntry = zipFile[i];

                    if (!zipEntry.IsFile)
                    {
                        continue;
                    }

                    if (i >= zipFile.Count - 1)
                    {
                        listString += zipEntry.Name;
                    }
                    else
                    {
                        listString += zipEntry.Name + Environment.NewLine;
                    }
                }
            }
            finally
            {
                if (zipFile != null)
                {
                    zipFile.Close();
                }
            }

            return(listString);
        }
Ejemplo n.º 13
0
        /// <summary>
        /// Extracts a Zip (as Stream) to the given OutFolder directory.
        /// </summary>
        /// <param name="zipStream"></param>
        /// <param name="outFolder"></param>
        private void ExtractZipFile(Stream zipStream, string outFolder)
        {
            var file = new ZipFile(zipStream);

            try
            {
                foreach (ZipEntry entry in file)
                {
                    if (entry.IsDirectory)
                    {
                        continue;
                    }
                    var fileName = entry.Name;

                    var entryStream = file.GetInputStream(entry);

                    var fullPath      = Path.Combine(outFolder, fileName);
                    var directoryName = Path.GetDirectoryName(fullPath);
                    if (!String.IsNullOrEmpty(directoryName))
                    {
                        Directory.CreateDirectory(directoryName);
                    }

                    // Unzip File in buffered chunks
                    using (var streamWriter = File.Create(fullPath))
                    {
                        entryStream.CopyTo(streamWriter, 4096);
                    }
                }
            }
            finally
            {
                if (file != null)
                {
                    file.Close();
                }
            }
        }
Ejemplo n.º 14
0
        /// <summary>
        /// Удаление файлов из zip архива
        /// Возвращает false, если архив 'битый' (не смог открыть), или не все файлы в нем удалось удалить
        /// </summary>
        /// <param name="SourceZipFile">Путь к исходному zip-файлу</param>
        /// <param name="FilesFromZipList">Файл для удаления</param>
        /// <param name="Password">пароль архива. Если его нет, то задаем null</param>
        public bool DeleteSelectedFiles(string SourceZipFile, ref List <string> FilesFromZipList, string Password)
        {
            // список файлов в архиве
            bool ret = false;

            if (File.Exists(SourceZipFile))
            {
                ZipFile zipFile = null;
                try {
                    zipFile = new ZipFile(SourceZipFile);
                } catch (Exception ex) {
                    Debug.DebugMessage(
                        SourceZipFile, ex, "SharpZipLibWorker.DeleteSelectedFiles(). Не возможно открыть архив."
                        );
                    return(false);
                }
                if (Password != null)
                {
                    zipFile.Password = Password;
                }

                zipFile.BeginUpdate();
                foreach (string file in FilesFromZipList)
                {
                    int fileExists = zipFile.FindEntry(file, false);
                    if (fileExists != -1)
                    {
                        if (zipFile[fileExists].IsFile)
                        {
                            ret &= zipFile.Delete(file);
                        }
                    }
                }
                zipFile.CommitUpdate();
                zipFile.Close();
            }
            return(ret);
        }
Ejemplo n.º 15
0
        public void FindEntry()
        {
            string tempFile = GetTempFilePath();

            Assert.IsNotNull(tempFile, "No permission to execute this test?");

            tempFile = Path.Combine(tempFile, "SharpZipTest.Zip");
            MakeZipFile(tempFile, new string[] { "Farriera", "Champagne", "Urban myth" }, 10, "Aha");

            using (ZipFile zipFile = new ZipFile(tempFile))
            {
                Assert.AreEqual(3, zipFile.Count, "Expected 1 entry");

                int testIndex = zipFile.FindEntry("Farriera", false);
                Assert.AreEqual(0, testIndex, "Case sensitive find failure");
                Assert.IsTrue(string.Compare(zipFile[testIndex].Name, "Farriera", StringComparison.Ordinal) == 0);

                testIndex = zipFile.FindEntry("Farriera", true);
                Assert.AreEqual(0, testIndex, "Case insensitive find failure");
                Assert.IsTrue(string.Compare(zipFile[testIndex].Name, "Farriera", StringComparison.OrdinalIgnoreCase) == 0);

                testIndex = zipFile.FindEntry("urban mYTH", false);
                Assert.AreEqual(-1, testIndex, "Case sensitive find failure");

                testIndex = zipFile.FindEntry("urban mYTH", true);
                Assert.AreEqual(2, testIndex, "Case insensitive find failure");
                Assert.IsTrue(string.Compare(zipFile[testIndex].Name, "urban mYTH", StringComparison.OrdinalIgnoreCase) == 0);

                testIndex = zipFile.FindEntry("Champane.", false);
                Assert.AreEqual(-1, testIndex, "Case sensitive find failure");

                testIndex = zipFile.FindEntry("Champane.", true);
                Assert.AreEqual(-1, testIndex, "Case insensitive find failure");

                zipFile.Close();
            }
            File.Delete(tempFile);
        }
Ejemplo n.º 16
0
        /// <summary>
        /// Gets location of the "document.xml" zip entry.
        /// </summary>
        /// <returns>Location of the "document.xml".</returns>
        private string FindDocumentXmlLocation()
        {
            using (ZipFile zip = new ZipFile(docxFile))
            {
                foreach (ZipEntry entry in zip)
                {
                    // Find "[Content_Types].xml" zip entry

                    if (string.Compare(entry.Name, "[Content_Types].xml", true) == 0)
                    {
                        Stream contentTypes = zip.GetInputStream(entry);

                        XmlDocument xmlDoc = new XmlDocument();
                        xmlDoc.PreserveWhitespace = true;
                        xmlDoc.Load(contentTypes);
                        contentTypes.Close();

                        //Create an XmlNamespaceManager for resolving namespaces

                        XmlNamespaceManager nsmgr = new XmlNamespaceManager(xmlDoc.NameTable);
                        nsmgr.AddNamespace("t", ContentTypeNamespace);

                        // Find location of "document.xml"

                        XmlNode node = xmlDoc.DocumentElement.SelectSingleNode(DocumentXmlXPath, nsmgr);

                        if (node != null)
                        {
                            string location = ((XmlElement)node).GetAttribute("PartName");
                            return(location.TrimStart(new char[] { '/' }));
                        }
                        break;
                    }
                }
                zip.Close();
            }
            return(null);
        }
Ejemplo n.º 17
0
        public static void UnZipAll(Stream stream, string outputDirectory, bool overrideExisting = false)
        {
            ZipFile zipFile = null;

            try
            {
                zipFile = new ZipFile(stream);

                foreach (ZipEntry entry in zipFile)
                {
                    if (!entry.IsFile)
                    {
                        continue;
                    }

                    Stream zstream = zipFile.GetInputStream(entry);

                    string filePath = Path.Combine(outputDirectory, entry.Name);
                    Directory.CreateDirectory(Path.GetDirectoryName(filePath));

                    if (!File.Exists(filePath) || overrideExisting)
                    {
                        using (FileStream sw = new FileStream(filePath, FileMode.Create))
                        {
                            zstream.CopyTo(sw);
                        }
                    }
                }
            }
            finally
            {
                if (null != zipFile)
                {
                    zipFile.IsStreamOwner = true;
                    zipFile.Close();
                }
            }
        }
Ejemplo n.º 18
0
        static List <string> GetZipEntryList(string fileName)
        {
            try
            {
                ZipFile zf = null;
                try
                {
                    List <string> entryList = new List <string>();
                    using (FileStream fs = File.OpenRead(fileName))
                    {
                        zf = new ZipFile(fs);
                        foreach (ZipEntry zipEntry in zf)
                        {
                            if (!zipEntry.IsFile)
                            {
                                continue; // Ignore directories
                            }

                            entryList.Add(zipEntry.Name);
                        }
                    }

                    return(entryList);
                }
                finally
                {
                    if (zf != null)
                    {
                        zf.IsStreamOwner = true; // Makes close also shut the underlying stream
                        zf.Close();              // Ensure we release resources
                    }
                }
            }
            catch (Exception)
            {
                return(null);
            }
        }
        /// <summary>
        /// http://netcoders.com.br/manipulacao-de-arquivos-zip-com-sharpziplib/
        /// </summary>
        /// <param name="souceZip"></param>
        private void CompactandoDocumento(string souceZip)
        {
            try
            {
                using (ZipFile arquivoZip =
                           ZipFile.Create(souceZip))
                {
                    arquivoZip.BeginUpdate();

                    foreach (string item in openFileDialog.FileNames)
                    {
                        arquivoZip.Add(item, item.Substring(item.LastIndexOf("\\") + 1));
                    }

                    arquivoZip.CommitUpdate();
                    arquivoZip.Close();
                }
            }
            catch (Exception)
            {
                throw;
            }
        }
Ejemplo n.º 20
0
        public void CreateEmptyArchive()
        {
            string tempFile = GetTempFilePath();

            Assert.IsNotNull(tempFile, "No permission to execute this test?");

            tempFile = Path.Combine(tempFile, "SharpZipTest.Zip");

            using (ZipFile f = ZipFile.Create(tempFile))
            {
                f.BeginUpdate();
                f.CommitUpdate();
                Assert.IsTrue(f.TestArchive(true));
                f.Close();
            }

            using (ZipFile f = new ZipFile(tempFile))
            {
                Assert.AreEqual(0, f.Count);
            }

            File.Delete(tempFile);
        }
Ejemplo n.º 21
0
        public void AddFile(string targetFile, Stream stream, string entryName)
        {
            if (File.Exists(targetFile) == false)
            {
                throw new FileNotFoundException(targetFile);
            }
            if (stream == null)
            {
                throw new ArgumentNullException();
            }
            if (String.IsNullOrEmpty(entryName))
            {
                throw new ArgumentNullException(entryName);
            }
            stream.Seek(0, SeekOrigin.Begin);
            ZipArchiveStreamDataSource dataSource = new ZipArchiveStreamDataSource(stream);
            ZipFile zipFile = new ZipFile(targetFile);

            zipFile.BeginUpdate();
            zipFile.Add(dataSource, entryName);
            zipFile.CommitUpdate();
            zipFile.Close();
        }
Ejemplo n.º 22
0
            private static ZipFile GetZipArchive(PakFileLump pak)
            {
                var pool = _sArchivePool ?? (_sArchivePool = new Dictionary <PakFileLump, ZipFile>());

                ZipFile archive;

                if (pool.TryGetValue(pak, out archive))
                {
                    return(archive);
                }

                archive = new ZipFile(pak._bspFile.GetLumpStream(pak.LumpType));

                pak.Disposing += _ =>
                {
                    pool.Remove(pak);
                    archive.Close();
                };

                pool.Add(pak, archive);

                return(archive);
            }
Ejemplo n.º 23
0
        public void RoundTrip()
        {
            string tempFile = GetTempFilePath();

            Assert.IsNotNull(tempFile, "No permission to execute this test?");

            tempFile = Path.Combine(tempFile, "SharpZipTest.Zip");

            try {
                MakeZipFile(tempFile, "", 10, 1024, "");

                using (ZipFile zipFile = new ZipFile(tempFile)) {
                    foreach (ZipEntry e in zipFile)
                    {
                        Stream instream = zipFile.GetInputStream(e);
                        CheckKnownEntry(instream, 1024);
                    }
                    zipFile.Close();
                }
            } finally {
                File.Delete(tempFile);
            }
        }
Ejemplo n.º 24
0
        public static Dictionary <string, byte[]> Unpack(byte[] data)
        {
            var     entries = new Dictionary <string, byte[]>();
            ZipFile zf      = null;

            try {
                MemoryStream fs = new MemoryStream(data);
                zf = new ZipFile(fs);
                foreach (ZipEntry zipEntry in zf)
                {
                    if (!zipEntry.IsFile)
                    {
                        continue;
                    }

                    byte[] buffer    = new byte[4096];
                    Stream zipStream = zf.GetInputStream(zipEntry);

                    using (MemoryStream streamWriter = new MemoryStream()) {
                        StreamUtils.Copy(zipStream, streamWriter, buffer);
                        entries.Add(zipEntry.Name, streamWriter.ToArray());
                    }
                }
            }
            catch (System.Exception e) {
                throw new System.InvalidOperationException("error while extracting the package due " + e.Message);
            }
            finally {
                if (zf != null)
                {
                    zf.IsStreamOwner = true;
                    zf.Close();
                }
            }

            return(entries);
        }
        ///
        /// Reads "document.xml" zip entry.
        ///
        /// Text containing in the document.
        private string ReadDocumentXml()
        {
            StringBuilder sb = new StringBuilder();

            ZipFile zip = OpenDocxFileAsZipFile();

            foreach (ZipEntry entry in zip)
            {
                if (string.Compare(entry.Name, docxFileLocation, true) == 0)
                {
                    Stream documentXml = zip.GetInputStream(entry);

                    XmlDocument xmlDoc = new XmlDocument();
                    xmlDoc.PreserveWhitespace = true;
                    xmlDoc.Load(documentXml);
                    documentXml.Close();

                    XmlNamespaceManager nsmgr =
                        new XmlNamespaceManager(xmlDoc.NameTable);
                    nsmgr.AddNamespace("w", WordprocessingMlNamespace);

                    XmlNode node =
                        xmlDoc.DocumentElement.SelectSingleNode(BodyXPath, nsmgr);

                    if (node == null)
                    {
                        return(string.Empty);
                    }

                    sb.Append(ReadNode(node));

                    break;
                }
            }
            zip.Close();
            return(sb.ToString());
        }
Ejemplo n.º 26
0
        public void FindEntriesInArchiveExtraData()
        {
            string tempFile = GetTempFilePath();

            Assert.IsNotNull(tempFile, "No permission to execute this test?");

            tempFile = Path.Combine(tempFile, "SharpZipTest.Zip");
            var        longComment = new String('A', 65535);
            FileStream tempStream  = File.Create(tempFile);

            MakeZipFile(tempStream, false, "", 1, 1, longComment);

            tempStream.WriteByte(85);
            tempStream.Close();

            bool fails = false;

            try
            {
                using (ZipFile zipFile = new ZipFile(tempFile))
                {
                    foreach (ZipEntry e in zipFile)
                    {
                        Stream instream = zipFile.GetInputStream(e);
                        CheckKnownEntry(instream, 1);
                    }
                    zipFile.Close();
                }
            }
            catch
            {
                fails = true;
            }

            File.Delete(tempFile);
            Assert.IsTrue(fails, "Currently zip file wont be found");
        }
Ejemplo n.º 27
0
        public static void ExtractFile(string packagePath, string fileName)
        {
            ZipFile zf = null;

            try {
                var fs = File.OpenRead(packagePath);

                zf = new ZipFile(fs);

                foreach (ZipEntry zipEntry in zf)
                {
                    if (!zipEntry.IsFile)
                    {
                        continue; // Ignore directories
                    }

                    var entryFileName = zipEntry.Name;

                    if (entryFileName == fileName)
                    {
                        var zipStream     = zf.GetInputStream(zipEntry);
                        var fullZipToPath = fileName;
                        var buffer        = new byte[4096];

                        using (var streamWriter = File.Create(fullZipToPath)) {
                            StreamUtils.Copy(zipStream, streamWriter, buffer);
                        }
                    }
                }
            } finally {
                if (zf != null)
                {
                    zf.IsStreamOwner = true; // Makes close also shut the underlying stream
                    zf.Close();              // Ensure we release resources
                }
            }
        }
Ejemplo n.º 28
0
        public void GetFile(string targetFile, string file, string outputFile)
        {
            if (File.Exists(targetFile) == false)
            {
                throw new FileNotFoundException(targetFile);
            }
            string   entryFile = file.Replace('\\', '/');
            ZipFile  zipFile   = new ZipFile(targetFile);
            ZipEntry entry     = zipFile.GetEntry(entryFile);

            if (entry == null)
            {
                throw new FileNotFoundException(file);
            }
            int size = 2048;

            byte[] data = new byte[2048];
            using (Stream stream = zipFile.GetInputStream(entry))
            {
                FileStream fs = File.Create(outputFile);
                while (true)
                {
                    size = stream.Read(data, 0, data.Length);
                    if (size > 0)
                    {
                        fs.Write(data, 0, size);
                    }
                    else
                    {
                        break;
                    }
                }
                fs.Close();
            }
            zipFile.Close();
            return;
        }
Ejemplo n.º 29
0
        public static void CreateZipfile(string outPathname, List <string> fileList)
        {
            try
            {
                if (!(new FileInfo(outPathname)).Exists)
                {
                    CreateEmptyZipfile(outPathname);
                }

                ZipFile zipFile = new ZipFile(outPathname);

                // Must call BeginUpdate to start, and CommitUpdate at the end.
                zipFile.BeginUpdate();
                Logger.info("CreateZipfile.BeginUpdate");

                // The "Add()" method will add or overwrite as necessary.
                // When the optional entryName parameter is omitted, the entry will be named
                // with the full folder path and without the drive e.g. "temp/folder/test1.txt".
                //
                foreach (string fileName in fileList)
                {
                    zipFile.Add(fileName, (new FileInfo(fileName)).Name);
                    Logger.info(string.Format("파일추가완료[{0}]", fileName));
                }
                // Continue calling .Add until finished.

                // Both CommitUpdate and Close must be called.
                zipFile.CommitUpdate();
                Logger.info("CreateZipfile.CommitUpdate");
                zipFile.Close();
            }
            catch (Exception ex)
            {
                Logger.error(ex.ToString());
                throw new Exception(string.Format("zipfile생성 중 에러발생[{0}]", outPathname));
            }
        }
Ejemplo n.º 30
0
        public static string MakeArchiveFromFiles(List <string> paths, string customPath = null)
        {
            try
            {
                string tempPath = customPath;
                if (String.IsNullOrEmpty(tempPath))
                {
                    tempPath = Path.GetTempPath();
                }
                //string tempPath = Path.GetTempPath();
                //string tempPath = "C:\\Users\\nedeljko\\Documents\\zipovi\\";

                string tempFile = DateTime.Now.ToString("dd_MM_yyyy_HH_mm_ss") + "_Documents.zip";

                string tempFilePath = Path.Combine(tempPath, tempFile);


                using (ZipFile f = ZipFile.Create(tempFilePath))
                {
                    f.BeginUpdate();

                    foreach (var item in paths)
                    {
                        string fileName = Path.GetFileName(item);
                        f.Add(item, fileName);
                    }
                    f.CommitUpdate();

                    f.Close();
                }

                return(tempFilePath);
            } catch (Exception ex)
            {
                return(null);
            }
        }
        private static void ProcessFile(File effDocFile, File outFile)
        {
            if (!effDocFile.exists())
            {
                throw new RuntimeException("file '" + effDocFile.GetAbsolutePath() + "' does not exist");
            }
            OutputStream os;
            try
            {
                os = new FileOutputStream(outFile);
            }
            catch (FileNotFoundException e)
            {
                throw new RuntimeException(e);
            }
            os = new SimpleAsciiOutputStream(os);
            PrintStream ps;
            try
            {
                ps = new PrintStream(os, true, "UTF-8");
            }
            catch (UnsupportedEncodingException e)
            {
                throw new RuntimeException(e);
            }

            outputLicenseHeader(ps);
            Type genClass = typeof(ExcelFileFormatDocFunctionExtractor);
            ps.println("# Created by (" + genClass.Name + ")");
            // identify the source file
            ps.print("# from source file '" + SOURCE_DOC_FILE_NAME + "'");
            ps.println(" (size=" + effDocFile.Length + ", md5=" + GetFileMD5(effDocFile) + ")");
            ps.println("#");
            ps.println("#Columns: (index, name, minParams, maxParams, returnClass, paramClasses, isVolatile, hasFootnote )");
            ps.println("");
            try
            {
                ZipFile zf = new ZipFile(effDocFile);
                InputStream is1 = zf.GetInputStream(zf.GetEntry("content.xml"));
                extractFunctionData(new FunctionDataCollector(ps), is1);
                zf.Close();
            }
            catch (ZipException e)
            {
                throw new RuntimeException(e);
            }
            catch (IOException e)
            {
                throw new RuntimeException(e);
            }
            ps.Close();

            String canonicalOutputFileName;
            try
            {
                canonicalOutputFileName = outFile.GetCanonicalPath();
            }
            catch (IOException e)
            {
                throw new RuntimeException(e);
            }
            Console.WriteLine("Successfully output to '" + canonicalOutputFileName + "'");
        }
Ejemplo n.º 32
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);
    }
Ejemplo n.º 33
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);
    }
 public bool RestoreData(int cacheID, RestoreTypes type)
 {
     byte[] tmp = FileCache.GetFileFromCache(cacheID);
     if (tmp == null)
         return false;
     bool ret=true;
     ZipFile zf = new ZipFile(new MemoryStream(tmp), true);
     switch (type)
     {
         case RestoreTypes.Database:
             foreach (ZipFile.sZippedFile zfi in zf.Files)
             {
                 if (zfi.Name == "database.rdpbk")
                 {
                     Stream ms = new MemoryStream(zfi.Data);
                     ret = BackupManager.RestoreDataFromStream(ConnectionPoolManager.GetPool(typeof(Extension)),
                         ref ms);
                 }
             }
             break;
         case RestoreTypes.Voicemail:
             Log.Trace("Cleaning out voicemail directory...");
             CleanDirectory(Settings.Current[Org.Reddragonit.FreeSwitchConfig.DataCore.Constants.BASE_PATH_NAME].ToString() + Path.DirectorySeparatorChar + Constants.DEFAULT_VOICEMAIL_PATH);
             Log.Trace("Examining all content within uploaded zip file...");
             foreach(sZippedFolder fold in zf.Folders)
             {
                 if (fold.Name == "voicemail")
                 {
                     RestoreFiles(fold, Settings.Current[Org.Reddragonit.FreeSwitchConfig.DataCore.Constants.BASE_PATH_NAME].ToString() + Path.DirectorySeparatorChar + Constants.DEFAULT_VOICEMAIL_PATH);
                     break;
                 }
             }
             foreach (ZipFile.sZippedFile file in zf.Files)
             {
                 if (file.Name == "voicemail_restore.sql")
                 {
                     Utility.ExecuteCommandToFreeswitchDB(FileDownloader.VM_DB, System.Text.ASCIIEncoding.ASCII.GetString(file.Data));
                     break;
                 }
             }
             break;
         case RestoreTypes.Recordings:
             Log.Trace("Cleaning out recordings directory...");
             CleanDirectory(Settings.Current[Org.Reddragonit.FreeSwitchConfig.DataCore.Constants.BASE_PATH_NAME].ToString() + Path.DirectorySeparatorChar + Org.Reddragonit.FreeSwitchConfig.DataCore.Constants.DEFAULT_RECORDINGS_DIRECTORY);
             Log.Trace("Examining all content within uploaded zip file...");
             foreach (sZippedFolder fold in zf.Folders)
             {
                 if (fold.Name == "recordings")
                 {
                     RestoreFiles(fold, Settings.Current[Org.Reddragonit.FreeSwitchConfig.DataCore.Constants.BASE_PATH_NAME].ToString() + Path.DirectorySeparatorChar + Org.Reddragonit.FreeSwitchConfig.DataCore.Constants.DEFAULT_RECORDINGS_DIRECTORY);
                 }
             }
             break;
         case RestoreTypes.Script:
             Log.Trace("Cleaning out scripts directory...");
             CleanDirectory(Settings.Current[Org.Reddragonit.FreeSwitchConfig.DataCore.Constants.BASE_PATH_NAME].ToString() + Path.DirectorySeparatorChar + Org.Reddragonit.FreeSwitchConfig.DataCore.Constants.DEFAULT_SCRIPTS_DIRECTORY);
             Log.Trace("Examining all content within uploaded zip file...");
             foreach (sZippedFolder fold in zf.Folders)
             {
                 if (fold.Name == "scripts")
                 {
                     RestoreFiles(fold,Settings.Current[Org.Reddragonit.FreeSwitchConfig.DataCore.Constants.BASE_PATH_NAME].ToString() + Path.DirectorySeparatorChar + Org.Reddragonit.FreeSwitchConfig.DataCore.Constants.DEFAULT_SCRIPTS_DIRECTORY);
                 }
             }
             break;
         case RestoreTypes.Sounds:
             Log.Trace("Cleaning out sounds directory...");
             CleanDirectory(Settings.Current[Org.Reddragonit.FreeSwitchConfig.DataCore.Constants.BASE_PATH_NAME].ToString() + Path.DirectorySeparatorChar + Org.Reddragonit.FreeSwitchConfig.DataCore.Constants.DEFAULT_SOUNDS_DIRECTORY);
             Log.Trace("Examining all content within uploaded zip file...");
             foreach (sZippedFolder fold in zf.Folders)
             {
                 if (fold.Name == "sounds")
                 {
                     RestoreFiles(fold, Settings.Current[Org.Reddragonit.FreeSwitchConfig.DataCore.Constants.BASE_PATH_NAME].ToString() + Path.DirectorySeparatorChar + Org.Reddragonit.FreeSwitchConfig.DataCore.Constants.DEFAULT_SOUNDS_DIRECTORY);
                 }
             }
             break;
         case RestoreTypes.Complete:
             Log.Trace("Cleaning out directories to perform complete restore...");
             CleanDirectory(Settings.Current[Org.Reddragonit.FreeSwitchConfig.DataCore.Constants.BASE_PATH_NAME].ToString() + Path.DirectorySeparatorChar + Constants.DEFAULT_VOICEMAIL_PATH);
             CleanDirectory(Settings.Current[Org.Reddragonit.FreeSwitchConfig.DataCore.Constants.BASE_PATH_NAME].ToString() + Path.DirectorySeparatorChar + Org.Reddragonit.FreeSwitchConfig.DataCore.Constants.DEFAULT_RECORDINGS_DIRECTORY);
             CleanDirectory(Settings.Current[Org.Reddragonit.FreeSwitchConfig.DataCore.Constants.BASE_PATH_NAME].ToString() + Path.DirectorySeparatorChar + Org.Reddragonit.FreeSwitchConfig.DataCore.Constants.DEFAULT_SCRIPTS_DIRECTORY);
             CleanDirectory(Settings.Current[Org.Reddragonit.FreeSwitchConfig.DataCore.Constants.BASE_PATH_NAME].ToString() + Path.DirectorySeparatorChar + Org.Reddragonit.FreeSwitchConfig.DataCore.Constants.DEFAULT_SOUNDS_DIRECTORY);
             Log.Trace("Restoring data from the zip file to the system...");
             foreach (sZippedFolder fold in zf.Folders)
             {
                 switch (fold.Name)
                 {
                     case "voicemail":
                         RestoreFiles(fold, Settings.Current[Org.Reddragonit.FreeSwitchConfig.DataCore.Constants.BASE_PATH_NAME].ToString() + Path.DirectorySeparatorChar + Constants.DEFAULT_VOICEMAIL_PATH);
                         break;
                     case "recordings":
                         RestoreFiles(fold, Settings.Current[Org.Reddragonit.FreeSwitchConfig.DataCore.Constants.BASE_PATH_NAME].ToString() + Path.DirectorySeparatorChar + Org.Reddragonit.FreeSwitchConfig.DataCore.Constants.DEFAULT_RECORDINGS_DIRECTORY);
                         break;
                     case "scripts":
                         RestoreFiles(fold, Settings.Current[Org.Reddragonit.FreeSwitchConfig.DataCore.Constants.BASE_PATH_NAME].ToString() + Path.DirectorySeparatorChar + Org.Reddragonit.FreeSwitchConfig.DataCore.Constants.DEFAULT_SCRIPTS_DIRECTORY);
                         break;
                     case "sounds":
                         RestoreFiles(fold, Settings.Current[Org.Reddragonit.FreeSwitchConfig.DataCore.Constants.BASE_PATH_NAME].ToString() + Path.DirectorySeparatorChar + Org.Reddragonit.FreeSwitchConfig.DataCore.Constants.DEFAULT_SOUNDS_DIRECTORY);
                         break;
                 }
             }
             foreach (ZipFile.sZippedFile zfi in zf.Files)
             {
                 switch (zfi.Name)
                 {
                     case "database.rdpbk":
                         Stream ms = new MemoryStream(zfi.Data);
                         ret = BackupManager.RestoreDataFromStream(ConnectionPoolManager.GetPool(typeof(Extension)),
                             ref ms);
                         break;
                     case "voicemail_restore.sql":
                         Utility.ExecuteCommandToFreeswitchDB(FileDownloader.VM_DB, System.Text.ASCIIEncoding.ASCII.GetString(zfi.Data));
                         break;
                 }
             }
             break;
     }
     zf.Close();
     return ret;
 }