Пример #1
0
 private static void Validation(ZipCompressOption option)
 {
     if (!option.Inputs.Any())
     {
         throw new ArgumentException("The input files cannot be empty.");
     }
 }
Пример #2
0
        public string Compress(ZipCompressOption option)
        {
            Validation(option);

            var outputFile = GetOutputFileName(option);

            if (File.Exists(outputFile) && option.FileOption == ZipFileOption.Default)
            {
                throw new InvalidOperationException($"File {outputFile} is existed.");
            }

            if (option.FileOption == ZipFileOption.OverwriteIfExisted)
            {
                File.Delete(outputFile);
            }

            using (var zip = option.FileOption == ZipFileOption.AppendIfExisted
                ? new ZipFile(outputFile) : ZipFile.Create(outputFile))
            {
                // Must call BeginUpdate to start, and CommitUpdate at the end.
                zip.BeginUpdate();

                if (option.Password.IsNotNullOrEmpty())
                {
                    zip.Password = option.Password;
                }

                foreach (var ip in option.Inputs)
                {
                    var full = Path.GetFullPath(ip);

                    if (PathEx.IsDirectory(full))
                    {
                        var folderOffset = Path.GetDirectoryName(full).Length + 1;
                        zip.AddDirectory(full, folderOffset);
                    }

                    // The "Add()" method will add or overwrite as necessary.
                    // When the optional entryName parameter is omitted, the entry will be named
                    else
                    {
                        zip.Add(full, Path.GetFileName(full));
                    }
                }

                // Both CommitUpdate and Close must be called.
                zip.CommitUpdate();
                zip.Close();
            }

            return(outputFile);
        }
Пример #3
0
        private string GetOutputFileName(ZipCompressOption option)
        {
            var output = string.Empty;

            if (option.OutputFile.IsNotNullOrEmpty())
            {
                return(Path.GetFullPath(option.OutputFile));
            }

            var f = Path.GetFullPath(option.Inputs.First());

            if (PathEx.IsDirectory(f))
            {
                return($"{Path.GetDirectoryName(f)}\\{new DirectoryInfo(f).Name}{Ext}");
            }
            return(Path.ChangeExtension(f, Ext));
        }