首页 > 解决方案 > 批量压缩 C# 中的文件

问题描述

我正在使用 Zip Archive 方法来压缩文件夹中的文件。但是,需要在特定时间从文件夹中读取最多 10 个文件并将其压缩。如果有大量文件,比如 100 个,则需要使用 C# 创建 10 个 zip 文件夹。

我如何实现这一目标?我已经在 Windows 表单中尝试过这个 -

private void btnZip_Click(object sender, EventArgs e) {  

    string FolderPathToZip = txtFolderPath.Text.Trim();  
    //To create unique file name with date and time with nanoseconds.  
    string ZipFileName = "D:\\backup\\bak-" + DateTime.Now.ToString("ddMMyyyy-HHmmssfffff") + ".zip";  
    try {  
        //To check whether D:\Backup folder exists or not.  
        //If not exists this will create a BACKUP folder.  
        if (Directory.Exists("D:\\backup")) {} else {  
            Directory.CreateDirectory("D:\\backup");  
        }  
        //TO create a zip file.  
        ZipFile.CreateFromDirectory(FolderPathToZip, ZipFileName);  
    } catch (Exception) {  
        //If system throw any exception message box will display "SOME ERROR"  
        MessageBox.Show("Some Error");  
    }  
    //Display successfully created message to the user.  
    MessageBox.Show("Zip Filename : " + ZipFileName + " Created Successfully");  
} 

标签: c#.net

解决方案


伪代码:

  1. 为文件所在的路径创建一个 DirectoryInfo 对象
  2. 使用 DirectoryInfo.GetFiles() 获取所有文件的列表 (*current)
  3. 在循环中 (i=0; 10*i<fileList.Count; i++) 执行以下操作

    • 子集 = fileList.Skip(10 * i).Take(10);
    • 循环这个子集并创建 Zip 存档

要开心 :)


推荐阅读