SharpZipLib. Создание архива файлов в цикле

288
22 марта 2017, 14:33

Добрый день!
Использую для создание архива библиотеку SharpZipLib.
Не получается в цикл передать список файлов и создать архив.
На данный момент он просто удаляет файлы.
Вот мой код:

using System;
using System.Data;
using Microsoft.SqlServer.Dts.Runtime;
using System.Windows.Forms;
using System.IO.Compression;
using ICSharpCode.SharpZipLib.Zip;
using ICSharpCode.SharpZipLib.Core;
     public void Main()
            {
                var myDate = DateTime.Now;
                var startOfMonth = new DateTime(myDate.Year, myDate.Month, 1);
                string rootFolderPath = @"E:\Download";
                string filesToDelete = @"*T_D_FD_DRYUA*";
                string[] fileList = System.IO.Directory.GetFiles(rootFolderPath, filesToDelete);
                if (DateTime.Now!= startOfMonth)
                {
                    foreach (string file in fileList)
                    {
                        //System.Diagnostics.Debug.WriteLine(file + "will be deleted");
                        //System.IO.File.Delete(file);

                        Dts.TaskResult = (int)ScriptResults.Success;
                    }
                 }
            }

Как с помощью этой библиотеки корректно создать архив необходимых файлов? Спасибо!

Answer 1

Создаёшь файл архива:

ZipFile zipFile = new ZipFile(@"c:\temp\existing.zip");

Добавляешь твои файлы:

public void Add() {
    ...
    foreach (string file in fileList)
    {
        UpdateExistingZip(file);
    }
}
public void UpdateExistingZip(string file) {

    // Must call BeginUpdate to start, and CommitUpdate at the end.
    zipFile.BeginUpdate();
    //zipFile.Password = "whatever"; // Only if a password is wanted on the new entry
    // 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".
    //
    //zipFile.Add(@"c:\temp\folder\test1.txt");
    zipFile.Add(file);
    // Specify the entryName parameter to modify the name as it appears in the zip.
    //
    //zipFile.Add(@"c:\temp\folder\test2.txt", "test2.txt");
    // Continue calling .Add until finished.
    // Both CommitUpdate and Close must be called.
    zipFile.CommitUpdate();
    zipFile.Close();
}

Сделано на основе этого https://github.com/icsharpcode/SharpZipLib/wiki/Updating . Работоспособность кода не проверял.

READ ALSO
Как применять unit test к ASP.NET MVC Database First

Как применять unit test к ASP.NET MVC Database First

В контроллере есть метод добавления новой записи в базу

242
Паттерн MVP для Windows Forms

Паттерн MVP для Windows Forms

У меня есть небольшой проект, который я хочу переписать, используя паттерн MVPПроект на платформе Windows Forms

303
Как соединить две окружности прямой

Как соединить две окружности прямой

Имеются две окружности одного радиуса R с центрами в точках x1, y1; x2, y2, с произвольным расположением

297
Какой инструмент выбрать для клиента и для работы с базой данных используя C#?

Какой инструмент выбрать для клиента и для работы с базой данных используя C#?

Какой инструмент выбрать для клиента и для работы с базой данных используя C#?

280