在C#中压缩每个文件而不是整个目录

时间:2018-08-13 20:32:03

标签: c# zipfile

我有一个控制台应用程序,可以生成多个pdf。我想要的是将这些单独的pdf转换为zip文件。我使用了ZipFile.CreateFromDirectory,但是它压缩了目录中的所有文件。有没有一种方法可以压缩每个生成的pdf文件。

更新:下面的代码根据Zakk的回答满足我的需要。

static void pdfandzip()
    {
        //Get the data from database into datatable
        string strQuery = ConfigurationManager.AppSettings["sql"];
        SqlCommand cmd = new SqlCommand(strQuery);
        DataTable dt = GetData(cmd);
        int i = 1;

        foreach (DataRow r in dt.Rows)
        {
            Document document = new Document();

            PdfWriter writer = PdfWriter.GetInstance(document, new FileStream("M://EmpsheetUpload/Pdf/Empsheet" + i + ".pdf", FileMode.Create));

            document.Open();
            iTextSharp.text.Font font5 = iTextSharp.text.FontFactory.GetFont(FontFactory.HELVETICA, 5);

            PdfPTable table = new PdfPTable(dt.Columns.Count);


            PdfPRow row = null;
            /*float[] widths = new float[] { 4f, 4f, 4f, 4f, 4f };

            table.SetWidths(widths);

            table.WidthPercentage = 100; */
            int iCol = 0;
            string colname = "";
            PdfPCell cell = new PdfPCell(new Phrase("EmpSheet"));

            cell.Colspan = dt.Columns.Count;

            foreach (DataColumn c in dt.Columns)
            {

                table.AddCell(new Phrase(c.ColumnName, font5));

            }


            if (dt.Rows.Count > 0)
            {
                table.CompleteRow();
                table.AddCell(new Phrase(r[0].ToString(), font5));
                table.AddCell(new Phrase(r[1].ToString(), font5));
                table.AddCell(new Phrase(r[2].ToString(), font5));
                table.AddCell(new Phrase(r[3].ToString(), font5));
                table.AddCell(new Phrase(r[4].ToString(), font5));
                table.AddCell(new Phrase(r[5].ToString(), font5));
                table.AddCell(new Phrase(r[6].ToString(), font5));
            }

            document.Add(table);
            document.Close();
            //ZipFile.CreateFromDirectory(@"M://EmpsheetUpload/Pdf", @"M://EmpsheetUpload/Zip/Empsheet" + i + ".zip");     
            string myPath = @"M:\\EmpsheetUpload\Pdf";
            var files = Directory.EnumerateFiles(myPath);
            foreach (var file in files)
            {
                var filename = file.Split('\\').Last();
                var folderName = filename.Substring(0, filename.IndexOf("."));
                if (Directory.Exists($@"M:\\EmpsheetUpload\Zip1"))
                    Directory.CreateDirectory($@"M:\\EmpsheetUpload\Zip");
                if (File.Exists($@"M:\\EmpsheetUpload\Pdf\Empsheet"+i+".pdf"))
                    File.Copy(file, $@"M:\\EmpsheetUpload\Zip\Empsheet" + i + ".pdf");
                if (File.Exists($@"M:\\EmpsheetUpload\Zip\Empsheet" + i + ".pdf"))
                    ZipFile.CreateFromDirectory($@"M:\\EmpsheetUpload\Zip", $@"M:\\EmpsheetUpload\Zip1\Empsheet"+i+".zip");
                Directory.Delete($@"M:\\EmpsheetUpload\Zip", true);
                i++;
            }

        }
    }

2 个答案:

答案 0 :(得分:1)

您可以使用 ZipArchive 类。下面是从链接复制的示例

using System;
using System.IO;
using System.IO.Compression;

namespace ConsoleApplication
{
    class Program
    {
        static void Main(string[] args)
        {
            using (FileStream zipToOpen = new FileStream(@"c:\users\exampleuser\release.zip", FileMode.Open))
            {
                using (ZipArchive archive = new ZipArchive(zipToOpen, ZipArchiveMode.Update))
                {
                    ZipArchiveEntry readmeEntry = archive.CreateEntry("Readme.txt");
                    using (StreamWriter writer = new StreamWriter(readmeEntry.Open()))
                    {
                            writer.WriteLine("Information about this package.");
                            writer.WriteLine("========================");
                    }
                }
            }
        }
    }
}

答案 1 :(得分:-1)

使用Directory.EnumerateFiles并循环遍历每个文件。 Directory.CreateDirectory(fileName_WITHOUT_EXTENSION)并复制文件。然后压缩该目录并清理您的文件夹。

在您的项目中添加对System.IO.Compression.FileSystem.dll的引用

这消除了安装外部库的需要

这是一个可行的例子

    static void Main(string[] args)
    {
        string myPath = @"C:\MYFILES";
        var files = Directory.EnumerateFiles(myPath);
        foreach (var file in files)
        {
            var filename = file.Split('\\').Last();
            var folderName = filename.Substring(0, filename.IndexOf("."));
            if (Directory.Exists($@"{myPath}\{folderName}"))
                Directory.Delete($@"{myPath}\{folderName}", true);
            Directory.CreateDirectory($@"{myPath}\{folderName}");
            if (File.Exists($@"{myPath}\{folderName}\{filename}"))
                File.Delete($@"{myPath}\{folderName}\{filename}");
            File.Copy(file, $@"{myPath}\{folderName}\{filename}" );
            if(File.Exists($@"{myPath}\{folderName}.zip"))
                File.Delete($@"{myPath}\{folderName}.zip");
            ZipFile.CreateFromDirectory($@"{myPath}\{folderName}", $@"{myPath}\{folderName}.zip");
            Directory.Delete($@"{myPath}\{folderName}", true);
        }
    }