Esempio n. 1
0
    protected void uploadFiles()
    {
        this.txtCaptcha.Text = "";
        bool dataOkay = false;

        dataOkay = this.FileUpload1.HasFile;
        if (dataOkay)
        {
            try
            {
                string fileName = this.FileUpload1.FileName;
                //this.SequenceNames.Add();
                this.FileUpload1.SaveAs(Path.Combine(this.ExpPath, fileName));

                using (ZipArchive archive = ZipFile.OpenRead(Path.Combine(this.ExpPath, fileName)))
                {
                    ZipFileExtensions.ExtractToDirectory(archive, ExpPath);
                }
                this.msg2.Visible = true;
                this.msg2.Text    = "Files uploaded successfully.";
            }
            catch (System.Exception)
            {
                this.msg2.Visible = true;
                this.msg2.Text    = "Error uploading files.";
            }
        }
    }
 //I assume you have a `Task.Run(() => Download(url, filePathDir);` calling this so it is on a background thread.
 public void Download(string url, string filePathDir)
 {
     WebClient wc = new WebClient();
     Stream zipReadingStream = wc.OpenRead(url);
     ZipArchive zip = new ZipArchive(zipReadingStream);
     ZipFileExtensions.ExtractToDirectory(zip, filePathDir, _progress);
 }
Esempio n. 3
0
        public static void Decompress(FileInfo fileToDecompress, Subtitle subtitle)
        {
            string newFileName = String.Empty;

            try
            {
                using (FileStream originalFileStream = fileToDecompress.OpenRead())
                {
                    string currentFileName = fileToDecompress.FullName;
                    newFileName = currentFileName.Remove(currentFileName.Length - fileToDecompress.Extension.Length);
                    newFileName = Path.Combine(subtitle.ParentDirectoryPath, subtitle.FileName);

                    using (FileStream decompressedFileStream = File.Create(newFileName))
                    {
                        using (GZipStream decompressionStream = new GZipStream(originalFileStream, CompressionMode.Decompress))
                        {
                            decompressionStream.CopyTo(decompressedFileStream);
                        }
                    }
                }
            } catch (Exception e) // Ako dekompresija ne uspije, probaj na drugi način
            {
                using (ZipArchive archive = ZipFile.OpenRead(fileToDecompress.FullName))
                {
                    foreach (ZipArchiveEntry entry in archive.Entries)
                    {
                        ZipFileExtensions.ExtractToFile(entry, newFileName, true);
                    }
                }
            }
        }
Esempio n. 4
0
        private static bool Extract(byte[] files, string directory)
        {
            using (var stream = new MemoryStream(files))
            {
                var Zip = new ZipArchive(stream);
                ZipFileExtensions.ExtractToDirectory(Zip, directory);
            }

            return(true);
        }
Esempio n. 5
0
        public void ZipIt()
        {
            var zipDirectoryAndFile = Factory.GetZipFile();

            using (var zip = ZipFile.Open(zipDirectoryAndFile, ZipArchiveMode.Create))
                ZipFileExtensions
                .CreateEntryFromFile(zip,
                                     Factory.GetFullFileName(),
                                     ConfigurationManager.AppSettings["MySqlDailyUpdateFileName"]);
        }
Esempio n. 6
0
        private async Task HandleManagedDlls(PackageIdentity packageIdentity, List <ZipArchiveEntry> zipArchiveEntries)
        {
            var entriesWithTargetFramework = zipArchiveEntries
                                             .Select(e => new { TargetFramework = NuGetFramework.Parse(e.FullName.Split('/')[1]), Entry = e }).ToList();

            if (_filterOurRefFiles)
            {
                entriesWithTargetFramework = entriesWithTargetFramework.Where(e => !string.Equals(e.Entry.FullName.Split('/')[0], "ref")).ToList();
            }

            var compatibleEntries       = entriesWithTargetFramework.Where(e => _compProvider.IsCompatible(_targetFramework, e.TargetFramework)).ToList();
            var mostCompatibleFramework = _reducer.GetNearest(_targetFramework, compatibleEntries.Select(x => x.TargetFramework));

            if (mostCompatibleFramework == null)
            {
                return;
            }

            var matchingEntries = entriesWithTargetFramework
                                  .Where(e => e.TargetFramework == mostCompatibleFramework).ToList();

            if (matchingEntries.Any())
            {
                var pluginAssemblies = new List <string>();

                foreach (var e in matchingEntries)
                {
                    ZipFileExtensions.ExtractToFile(e.Entry, Path.Combine(_root, e.Entry.Name), overwrite: true);

                    var installedDllInfo = new DllInfo
                    {
                        RelativeFilePath         = Path.Combine(packageIdentity.ToString(), e.Entry.FullName),
                        FullFilePath             = Path.Combine(_root, packageIdentity.ToString(), e.Entry.FullName),
                        FileName                 = e.Entry.Name,
                        TargetFrameworkName      = e.TargetFramework.ToString(),
                        TargetFrameworkShortName = e.TargetFramework.GetShortFolderName(),
                        PackageIdentity          = packageIdentity.Id,
                        TargetVersion            = e.TargetFramework.Version.ToString()
                    };

                    InstalledDlls.Add(installedDllInfo);

                    if (packageIdentity.Id == _pluginNuGetPackage.Identity.Id)
                    {
                        pluginAssemblies.Add(e.Entry.Name);
                    }
                }

                await File.WriteAllLinesAsync(Path.Combine(_root, PluginAssemblyFilesFileName), pluginAssemblies);
            }
        }
        private void CreateAndSaveArchive(String path)
        {
            if (File.Exists(path))
            {
                File.Delete(path);
            }

            System.IO.Compression.ZipFile.CreateFromDirectory("temp", path, CompressionLevel.Optimal, true);

            using (ZipArchive arc = System.IO.Compression.ZipFile.Open(path, ZipArchiveMode.Update))
            {
                ZipFileExtensions.CreateEntryFromFile(arc, Names.Database, Names.TempBDFile, CompressionLevel.Optimal);
            }
        }
Esempio n. 8
0
 public static void AddFiles(Dictionary <string, List <string> > filesByRootPath, string outputName)
 {
     using (var zipToOpen = new FileStream(outputName, FileMode.Create))
         using (var archive = new ZipArchive(zipToOpen, ZipArchiveMode.Create))
         {
             foreach (var files in filesByRootPath)
             {
                 foreach (var file in files.Value)
                 {
                     var name = Path.GetRelativePath(files.Key, file);
                     ZipFileExtensions.CreateEntryFromFile(archive, file, name);
                 }
             }
         }
 }
Esempio n. 9
0
 // Read archive of KMZ file and save to upload folder
 private void ReadArchiveAndExport(string pathToimage)
 {
     using (ZipArchive archive = ZipFile.Open(path, ZipArchiveMode.Read))
     {
         if (pathToimage != null && map != null)
         {
             ZipArchiveEntry entry = archive.GetEntry(pathToimage);
             string          name  = Path.GetRandomFileName() + "." + entry.Name;
             while (File.Exists(Path.Combine(rootPath, name)))
             {
                 name = Path.GetRandomFileName() + "." + entry.Name;
             }
             ZipFileExtensions.ExtractToFile(entry, Path.Combine(rootPath, name));
             map.PathToFile = Path.Combine(completePath, name);
         }
     }
 }
        private async Task <string> GetTextFromLaTeXZip(MemoryStream ms)
        {
            var tmpPath = Path.Combine(Path.GetTempPath(), Path.GetRandomFileName().Replace(".", ""));

            Directory.CreateDirectory(tmpPath);

            try
            {
                try
                {
                    ms.Seek(0, SeekOrigin.Begin);
                    var zipFile = new ZipArchive(ms);
                    ZipFileExtensions.ExtractToDirectory(zipFile, tmpPath, true);
                }
                catch (Exception)
                {
                    _logger.LogInformation("Received file is not a zip file. GetTextFromLaTeXZip will return null.");
                    return(null);
                }

                var tmpFile = Path.Combine(tmpPath, "main.tex");
                if (!System.IO.File.Exists(tmpFile))
                {
                    _logger.LogInformation("main.tex not found in the received zip file. GetTextFromLaTeXZip will return null.");
                    return(null);
                }

                RunCommand($"cd \"{tmpPath}\" && untex -m -o -e -a -i {tmpFile} > {tmpFile}.txt");
                var textData = await System.IO.File.ReadAllBytesAsync(tmpFile + ".txt");

                var text = Encoding.UTF8.GetString(textData);
                return(text);
            }
            catch (Exception ex)
            {
                _logger.LogWarning($"GetTextFromLaTeXZip failed: {ex}");
                return(null);
            }
            finally
            {
                if (Directory.Exists(tmpPath))
                {
                    Directory.Delete(tmpPath, true);
                }
            }
        }
Esempio n. 11
0
        private static async Task DownloadData()
        {
            using (var client = new HttpClient())
            {
                var response = await client.GetStreamAsync("https://github.com/luisquintanilla/machinelearning-samples/raw/AB1608219/samples/modelbuilder/MulticlassClassification_RestaurantViolations/RestaurantScores.zip");

                using (var archive = new ZipArchive(response))
                {
                    foreach (var file in archive.Entries)
                    {
                        if (Path.GetExtension(file.FullName) == ".tsv")
                        {
                            ZipFileExtensions.ExtractToFile(file, GetAbsolutePath(TRAIN_DATA_FILEPATH));
                        }
                    }
                }
            }
        }
Esempio n. 12
0
        public static void CreateFromDirectory(string sourcePath, string outputName)
        {
            var files = new List <string>(Directory.GetFiles(sourcePath, "", SearchOption.AllDirectories));

            using (var zipToOpen = new FileStream(outputName, FileMode.Create))
                using (var archive = new ZipArchive(zipToOpen, ZipArchiveMode.Create))
                {
                    foreach (var file in files)
                    {
                        var name = Path.GetRelativePath(sourcePath, file);
                        if (GetTopDirectory(name).Equals(ParentZipEntryFolder, StringComparison.InvariantCultureIgnoreCase))
                        {
                            name = name.Substring(ParentZipEntryFolder.Length, name.Length - ParentZipEntryFolder.Length);
                        }
                        ZipFileExtensions.CreateEntryFromFile(archive, file, name);
                    }
                }
        }
Esempio n. 13
0
        public void CopyAppResources(string msAppPath, string sourcePath, string destinationPath)
        {
            if (string.IsNullOrWhiteSpace(sourcePath) ||
                string.IsNullOrWhiteSpace(destinationPath))
            {
                throw new ArgumentNullException("App path is null or empty.");
            }

            CreateDirectoryIfNotExist(destinationPath);

            var assetPath = Path.Combine(sourcePath, AppFileName.AssetsDirectoryName);

            if (Directory.Exists(assetPath))
            {
                var assetFilesPath = new List <string>();

                var directoryList = Directory.GetDirectories(assetPath)?.ToList() ?? new List <string>();
                directoryList.Add(assetPath);

                directoryList?.ForEach(r =>
                {
                    //  CreateDirectoryIfNotExist(r.Replace(sourcePath, destinationPath));
                    var filePath = Directory.GetFiles(r)?.ToList();
                    if (filePath != null && filePath.Count > 0)
                    {
                        assetFilesPath.AddRange(filePath);
                    }
                });

                foreach (string file in assetFilesPath)
                {
                    using (FileStream zipToOpen = new FileStream(msAppPath, FileMode.Open))
                    {
                        using (ZipArchive archive = new ZipArchive(zipToOpen, ZipArchiveMode.Update))
                        {
                            string entryName = file.Substring(file.IndexOf(AppFileName.AssetsDirectoryName));
                            ZipFileExtensions.CreateEntryFromFile(archive, file, entryName);
                        }
                    }
                }
            }
        }
Esempio n. 14
0
        public void ExtractArchive(ZipArchive archive)
        {
            foreach (var entry in archive.Entries)
            {
                entry.ExtractToFile(""); // Noncompliant
//              ^^^^^^^^^^^^^^^^^^^^^^^
            }

            for (int i = 0; i < archive.Entries.Count; i++)
            {
                archive.Entries[i].ExtractToFile(""); // Noncompliant
            }

            archive.Entries.ToList()
            .ForEach(e => e.ExtractToFile(""));     // Noncompliant
//                            ^^^^^^^^^^^^^^^^^^^

            ZipFileExtensions.ExtractToDirectory(archive, ""); // Noncompliant
            archive.ExtractToDirectory("");                    // Noncompliant
        }
        public void ExtractEntry(ZipArchiveEntry entry)
        {
            string fullName;
            Stream stream;

            entry.ExtractToFile("");                          // Noncompliant
            entry.ExtractToFile("", true);                    // Noncompliant

            ZipFileExtensions.ExtractToFile(entry, "");       // Noncompliant
            ZipFileExtensions.ExtractToFile(entry, "", true); // Noncompliant

            stream = entry.Open();                            // Noncompliant

            entry.Delete();                                   // Compliant, method is not tracked

            fullName = entry.FullName;                        // Compliant, properties are not tracked

            ExtractToFile(entry);                             // Compliant, method is not tracked

            Invoke(ZipFileExtensions.ExtractToFile);          // Compliant, not an invocation, but could be considered as FN
        }
Esempio n. 16
0
        public static bool downloadLibrary(Library lib, string targetFolder)
        {
            string versionedLibFolder   = Path.Combine(targetFolder, Path.GetFileNameWithoutExtension(lib.url));
            string unversionedLibFolder = versionedLibFolder.Substring(0, versionedLibFolder.LastIndexOf('-'));

            if (Directory.Exists(unversionedLibFolder))
            {
                return(false);
            }

            WebClient    client       = null;
            MemoryStream zippedStream = null;
            ZipArchive   libArchive   = null;

            try
            {
                client       = new WebClient();
                zippedStream = new MemoryStream(client.DownloadData(lib.url));
                libArchive   = new ZipArchive(zippedStream);
                ZipFileExtensions.ExtractToDirectory(libArchive, targetFolder);

                Directory.Move(versionedLibFolder, unversionedLibFolder);
                return(true);
            }
            catch //(Exception ex)
            {
                return(false);
            }
            finally
            {
                if (Directory.Exists(versionedLibFolder))
                {
                    Directory.Delete(versionedLibFolder);
                }
                client?.Dispose();
                zippedStream?.Dispose();
                libArchive?.Dispose();
            }
        }
        private static string GetCliVersion(string path)
        {
            string cliVersion = string.Empty;

            foreach (string file in Directory.GetFiles(path, "*", SearchOption.AllDirectories))
            {
                if (file.EndsWith(".zip"))
                {
                    var zip = ZipFile.OpenRead(file);
                    foreach (var entry in zip.Entries)
                    {
                        if (entry.Name == "func.dll")
                        {
                            ZipFileExtensions.ExtractToFile(entry, "func.dll", true);
                            cliVersion = FileVersionInfo.GetVersionInfo(".\\func.dll").FileVersion;
                            break;
                        }
                    }
                }
            }
            return(cliVersion);
        }
        /// <summary>
        /// Zips a set of files (that must be rooted at the given RootDir) to a set of zip files in the given OutputDir. The files will be prefixed with the given basename.
        /// </summary>
        /// <param name="Files">Fully qualified list of files to zip (must be rooted at RootDir).</param>
        /// <param name="RootDir">Root Directory where all files will be extracted.</param>
        /// <param name="OutputDir">Location to place the set of zip files created.</param>
        /// <param name="StagingDir">Location to create zip files before copying them to the OutputDir. If the OutputDir is on a remote file share, staging may be more efficient. Use null to avoid using a staging copy.</param>
        /// <param name="ZipBaseName">The basename of the set of zip files.</param>
        /// <returns>Some metrics about the zip process.</returns>
        /// <remarks>
        /// This function tries to zip the files in parallel as fast as it can. It makes no guarantees about how many zip files will be created or which files will be in which zip,
        /// but it does try to reasonably balance the file sizes.
        /// </remarks>
        private static FileInfo[] ParallelZipFiles(FileInfo[] InputFiles, DirectoryReference RootDir, DirectoryReference OutputDir, DirectoryReference StagingDir, string ZipBaseName)
        {
            // First get the sizes of all the files. We won't parallelize if there isn't enough data to keep the number of zips down.
            var FilesInfo = InputFiles
                            .Select(InputFile => new { File = new FileReference(InputFile), FileSize = InputFile.Length })
                            .ToList();

            // Profiling results show that we can zip 100MB quite fast and it is not worth parallelizing that case and creating a bunch of zips that are relatively small.
            const long MinFileSizeToZipInParallel = 1024 * 1024 * 100L;
            var        bZipInParallel             = FilesInfo.Sum(FileInfo => FileInfo.FileSize) >= MinFileSizeToZipInParallel;

            // order the files in descending order so our threads pick up the biggest ones first.
            // We want to end with the smaller files to more effectively fill in the gaps
            var FilesToZip = new ConcurrentQueue <FileReference>(FilesInfo.OrderByDescending(FileInfo => FileInfo.FileSize).Select(FileInfo => FileInfo.File));

            // We deliberately avoid Parallel.ForEach here because profiles have shown that dynamic partitioning creates
            // too many zip files, and they can be of too varying size, creating uneven work when unzipping later,
            // as ZipFile cannot unzip files in parallel from a single archive.
            // We can safely assume the build system will not be doing more important things at the same time, so we simply use all our logical cores,
            // which has shown to be optimal via profiling, and limits the number of resulting zip files to the number of logical cores.
            //
            // Sadly, mono implementation of System.IO.Compression is really poor (as of 2015/Aug), causing OOM when parallel zipping a large set of files.
            // However, Ionic is MUCH slower than .NET's native implementation (2x+ slower in our build farm), so we stick to the faster solution on PC.
            // The code duplication in the threadprocs is unfortunate here, and hopefully we can settle on .NET's implementation on both platforms eventually.
            List <Thread> ZipThreads;

            ConcurrentBag <FileInfo> ZipFiles = new ConcurrentBag <FileInfo>();

            DirectoryReference ZipDir = StagingDir ?? OutputDir;

            if (Utils.IsRunningOnMono)
            {
                ZipThreads = (
                    from CoreNum in Enumerable.Range(0, bZipInParallel ? Environment.ProcessorCount : 1)
                    let ZipFileName = FileReference.Combine(ZipDir, string.Format("{0}{1}.zip", ZipBaseName, bZipInParallel ? "-" + CoreNum.ToString("00") : ""))
                                      select new Thread(() =>
                {
                    // don't create the zip unless we have at least one file to add
                    FileReference File;
                    if (FilesToZip.TryDequeue(out File))
                    {
                        // Create one zip per thread using the given basename
                        using (var ZipArchive = new Ionic.Zip.ZipFile(ZipFileName.FullName)
                        {
                            CompressionLevel = Ionic.Zlib.CompressionLevel.BestSpeed
                        })
                        {
                            // pull from the queue until we are out of files.
                            do
                            {
                                // use fastest compression. In our best case we are CPU bound, so this is a good tradeoff,
                                // cutting overall time by 2/3 while only modestly increasing the compression ratio (22.7% -> 23.8% for RootEditor PDBs).
                                // This is in cases of a super hot cache, so the operation was largely CPU bound.
                                ZipArchive.AddFile(File.FullName, CommandUtils.ConvertSeparators(PathSeparator.Slash, File.Directory.MakeRelativeTo(RootDir)));
                            } while (FilesToZip.TryDequeue(out File));
                            ZipArchive.Save();
                        }
                        // if we are using a staging dir, copy to the final location and delete the staged copy.
                        FileInfo ZipFile = new FileInfo(ZipFileName.FullName);
                        if (StagingDir != null)
                        {
                            FileInfo NewZipFile = ZipFile.CopyTo(CommandUtils.MakeRerootedFilePath(ZipFile.FullName, StagingDir.FullName, OutputDir.FullName));
                            ZipFile.Delete();
                            ZipFile = NewZipFile;
                        }
                        ZipFiles.Add(ZipFile);
                    }
                })).ToList();
            }
            else
            {
                ZipThreads = (
                    from CoreNum in Enumerable.Range(0, bZipInParallel ? Environment.ProcessorCount : 1)
                    let ZipFileName = FileReference.Combine(ZipDir, string.Format("{0}{1}.zip", ZipBaseName, bZipInParallel ? "-" + CoreNum.ToString("00") : ""))
                                      select new Thread(() =>
                {
                    // don't create the zip unless we have at least one file to add
                    FileReference File;
                    if (FilesToZip.TryDequeue(out File))
                    {
                        // Create one zip per thread using the given basename
                        using (var ZipArchive = System.IO.Compression.ZipFile.Open(ZipFileName.FullName, System.IO.Compression.ZipArchiveMode.Create))
                        {
                            // pull from the queue until we are out of files.
                            do
                            {
                                // use fastest compression. In our best case we are CPU bound, so this is a good tradeoff,
                                // cutting overall time by 2/3 while only modestly increasing the compression ratio (22.7% -> 23.8% for RootEditor PDBs).
                                // This is in cases of a super hot cache, so the operation was largely CPU bound.
                                // Also, sadly, mono appears to have a bug where nothing you can do will properly set the LastWriteTime on the created entry,
                                // so we have to ignore timestamps on files extracted from a zip, since it may have been created on a Mac.
                                ZipFileExtensions.CreateEntryFromFile(ZipArchive, File.FullName, CommandUtils.ConvertSeparators(PathSeparator.Slash, File.MakeRelativeTo(RootDir)), System.IO.Compression.CompressionLevel.Fastest);
                            } while (FilesToZip.TryDequeue(out File));
                        }
                        // if we are using a staging dir, copy to the final location and delete the staged copy.
                        FileInfo ZipFile = new FileInfo(ZipFileName.FullName);
                        if (StagingDir != null)
                        {
                            FileInfo NewZipFile = ZipFile.CopyTo(CommandUtils.MakeRerootedFilePath(ZipFile.FullName, StagingDir.FullName, OutputDir.FullName));
                            ZipFile.Delete();
                            ZipFile = NewZipFile;
                        }
                        ZipFiles.Add(ZipFile);
                    }
                })).ToList();
            }
            ZipThreads.ForEach(thread => thread.Start());
            ZipThreads.ForEach(thread => thread.Join());

            return(ZipFiles.OrderBy(x => x.Name).ToArray());
        }
Esempio n. 19
0
        public MEFLoader()
        {
            RemoveTrash();

            #region Update process
            var baseUpdateDir = new DirectoryInfo("plugins\\updates");

            if (baseUpdateDir.Exists)
            {
                foreach (var pluginContainer in baseUpdateDir.GetFiles("*.bpl"))
                {
                    try
                    {
                        ValidatePluginContainer(pluginContainer);

                        using (var zip = new ZipArchive(new FileStream(pluginContainer.FullName, FileMode.Open)))
                        {
                            var entry = zip.GetEntry("plugin.definition");

                            if (null != entry)
                            {
                                using (var tr = new System.IO.StreamReader(entry.Open()))
                                {
                                    IniFile definition = new IniFile(tr);

                                    var name          = definition.GetValue("plugin", "name");
                                    var version       = definition.GetValue("plugin", "version");
                                    var bitness       = definition.GetValue("plugin", "bitness");
                                    var installpath   = definition.GetValue("plugin", "installpath");
                                    var contentfolder = definition.GetValue("plugin", "contentfolder");

                                    Logger.Info(String.Format("Installing or updating plugin by plugincontainer."));
                                    Logger.Info(String.Format("   Plugin container file: {0}", pluginContainer.FullName));
                                    Logger.Info(String.Format("   Plugin bitness: {0}", bitness));
                                    Logger.Info(String.Format("   Plugin installpath: {0}", installpath));
                                    Logger.Info(String.Format("   Plugin version: {0}", version));
                                    String target = Path.Combine(Environment.GetEnvironmentVariable("appdata"),
                                                                 "beRemote", "tmp", contentfolder);
                                    ZipFileExtensions.ExtractToDirectory(zip, target);

                                    var contentDir = new DirectoryInfo(Path.Combine(target, contentfolder));
                                    var targetDir  = new DirectoryInfo((installpath.StartsWith("\\")) ? installpath.Remove(0, 1) : installpath);

                                    foreach (var file in contentDir.GetFiles())
                                    {
                                        file.MoveTo(Path.Combine(targetDir.FullName, file.Name));
                                    }

                                    foreach (var dir in contentDir.GetDirectories())
                                    {
                                        dir.MoveTo(Path.Combine(targetDir.FullName, dir.Name));
                                    }

                                    Logger.Info(String.Format("Plugin installed, deleting container"));

                                    Directory.Delete(target, true);
                                }
                            }
                        }

                        pluginContainer.Delete();
                    }
                    catch (Exception ex)
                    {
                        new beRemoteException(beRemoteExInfoPackage.SignificantInformationPackage,
                                              "Plugin container is invalid. Removing it from updater.", ex);

                        pluginContainer.Delete();
                    }
                }
            }
            #endregion
        }
Esempio n. 20
0
        public override bool Execute()
        {
            Log.LogMessage(MessageImportance.High, "AddToZipTask-asm called", null);

            CompressionLevel level = CompressionLevel.Optimal;

            if (!string.IsNullOrWhiteSpace(Compression))
            {
                try {
                    CompressionLevel result = (CompressionLevel)Enum.Parse(typeof(CompressionLevel), Compression);
                    level = result;
                }
                catch (Exception ex) {
                    Log.LogWarning("Unable to parse compression level [{0}]. Error [{1}]", Compression, ex.ToString());
                }
            }

            string parentDir = Path.GetDirectoryName(ZipFilePath);

            if (!Directory.Exists(parentDir))
            {
                Directory.CreateDirectory(parentDir);
            }
            // System.Diagnostics.Debugger.Launch();
            try{
                using (ZipArchive zip = ZipFile.Open(ZipFilePath, System.IO.Compression.ZipArchiveMode.Update)) {
                    Uri rootFolderUri = new Uri(RootFolder);
                    // add each input file to the zip
                    foreach (var file in FilesToAdd)
                    {
                        // get the relative path of the file to to add
                        string filePath = file.GetMetadata("FullPath");
                        Uri    fileUri  = new Uri(filePath);
                        string relpath  = Uri.UnescapeDataString(
                            rootFolderUri.MakeRelativeUri(fileUri)
                            .ToString()
                            .Replace('/', Path.DirectorySeparatorChar)
                            );

                        Log.LogMessage("Update zip: [{0}], add file: [{1}], relpath: [{2}]", ZipFilePath, filePath, relpath);

                        // var entriesToDelete = new List<ZipArchiveEntry>();
                        // if the file is already in the zip remove it and add again
                        if (zip.Entries != null && zip.Entries.Count > 0)
                        {
                            List <ZipArchiveEntry> entries = zip.Entries.ToList();
                            foreach (var entry in entries)
                            {
                                if (entry.FullName.Equals(relpath, StringComparison.OrdinalIgnoreCase))
                                {
                                    // entriesToDelete.Add(entry);
                                    Log.LogMessage(MessageImportance.Low, "deleting zip entry for [{0}]", relpath);
                                    entry.Delete();
                                }
                            }
                        }
                        //if(entriesToDelete != null && entriesToDelete.Count > 0){
                        //    foreach(var entry in entriesToDelete) {
                        //        try {
                        //            entry.Delete();
                        //        }
                        //        catch(Exception ex){
                        //            Log.LogMessage(MessageImportance.Low, "Unable to delete entry from zip. {0}", ex.ToString());
                        //        }
                        //    }
                        //}
                        ZipFileExtensions.CreateEntryFromFile(zip, filePath, relpath, level);
                    }
                }
            }
            catch (Exception ex) {
                Log.LogError(ex.ToString());
                return(false);
            }

            return(true);
        }
Esempio n. 21
0
        public static void CreateFromDirectory(string sourceDirectoryName, string destinationArchiveFileName, bool includeBaseDirectory)
        {
            // Rely on Path.GetFullPath for validation of sourceDirectoryName and destinationArchive

            // Checking of compressionLevel is passed down to DeflateStream and the IDeflater implementation
            // as it is a pluggable component that completely encapsulates the meaning of compressionLevel.

            sourceDirectoryName        = Path.GetFullPath(sourceDirectoryName);
            destinationArchiveFileName = Path.GetFullPath(destinationArchiveFileName);

            var root = new FileInfo(destinationArchiveFileName).DirectoryName;

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

            //add files and directories
            DirectoryInfo di = new DirectoryInfo(sourceDirectoryName);

            if (di.GetFiles().Length == 0)
            {
                return;
            }

            using (ZipArchive archive = Open(destinationArchiveFileName, ZipArchiveMode.Create)) {
                bool directoryIsEmpty = true;

                string basePath = di.FullName;

                if (includeBaseDirectory && di.Parent != null)
                {
                    basePath = di.Parent.FullName;
                }

                // Windows' MaxPath (260) is used as an arbitrary default capacity, as it is likely
                // to be greater than the length of typical entry names from the file system, even
                // on non-Windows platforms. The capacity will be increased, if needed.
                const int DefaultCapacity = 260;
                char[]    entryNameBuffer = ArrayPool <char> .Shared.Rent(DefaultCapacity);

                try {
                    foreach (FileSystemInfo file in di.EnumerateFileSystemInfos("*.log", SearchOption.TopDirectoryOnly))
                    {
                        directoryIsEmpty = false;

                        int entryNameLength = file.FullName.Length - basePath.Length;

                        // Create entry for file:
                        string entryName = ZipFileUtils.EntryFromPath(file.FullName, basePath.Length, entryNameLength,
                                                                      ref entryNameBuffer);
                        ZipFileExtensions.CreateEntryFromFile(archive, file.FullName, entryName);

                        // 创建后删除
                        file.Delete();
                    } // foreach

                    // If no entries create an empty root directory entry:
                    if (includeBaseDirectory && directoryIsEmpty)
                    {
                        archive.CreateEntry(ZipFileUtils.EntryFromPath(di.Name, 0, di.Name.Length, ref entryNameBuffer,
                                                                       appendPathSeparator: true));
                    }
                }
                catch (Exception ex) {
                    IoC.Resolve <ILogger <MonitorZipFileHelper> >().LogError(ex, "MonitorZipFileHelper CreateFromDirectory error.");
                }
                finally {
                    ArrayPool <char> .Shared.Return(entryNameBuffer);
                }
            }
        }