Exemplo n.º 1
0
        public void Compress(string targetDirectory)
        {
            var config = JsonConfiguration.Configuration;
            var logger = Logger.Global;

            Parallel.ForEach(Files, new ParallelOptions()
            {
                MaxDegreeOfParallelism = config.MaxThreads != 0 ? config.MaxThreads : Environment.ProcessorCount
            },
                             f => {
                var relPath        = BaseDirectory.RelativePath(f.Path);
                var targetFileName = Path.Combine(targetDirectory, relPath + ".bz2");
                Directory.CreateDirectory(Path.GetDirectoryName(targetFileName));

                var fi = new FileInfo(f.Path);
                if (fi.Length <= config.CompressionOptions.MinimumSize)
                {
                    logger.Write($"Moving file {relPath} because the size is below the MinimumSize.");
                    File.Move(f.Path, targetFileName);
                    return;
                }

                using (var sourceFile = new FileStream(f.Path, FileMode.Open, FileAccess.Read, FileShare.Read))
                {
                    using (var targetFile = new FileStream(targetFileName, FileMode.OpenOrCreate, FileAccess.Write, FileShare.None))
                    {
                        try
                        {
                            logger.Write($"Compressing file {relPath}");
                            BZip2.Compress(sourceFile, targetFile, true, config.CompressionOptions.Level);
                        }
                        catch (Exception ex)
                        {
                            logger.Write(ex, $"Could not compress {relPath}");
                        }
                    }
                }
            });
        }