使用 ZipFile 压缩文件时出现错误

Getting error when compressing file with ZipFile

我正在使用 Windows 表单申请。在我的应用程序中,我使用了 FolderBrowserDialogtextbox1 和两个按钮。在我的文本框中,我正在传递文件夹。从文件夹中,它将 select 特定的文件类型。获得此类文件类型后,我需要使用 ZipFile 对其进行转换,即 Iconic.zip。检索特定文件类型后,它向我显示 FileNotfound 错误。出于测试目的,我尝试将检索到的文件显示到列表框,并且运行良好。但是当我通过 ZipFile 调用时它给我错误,无法弄清楚错误是什么。

namespace WinDataStore
{
    public partial class Form1 : Form
    {


        public Form1()
        {
            InitializeComponent();

        }

        private void button1_Click(object sender, EventArgs e)
        {            
            FolderBrowserDialog folderBrowserDlg = new FolderBrowserDialog();
            folderBrowserDlg.ShowNewFolderButton = true;         
            DialogResult dlgResult = folderBrowserDlg.ShowDialog();
            if (dlgResult.Equals(DialogResult.OK))
            {                
                textBox1.Text = folderBrowserDlg.SelectedPath;              
               Environment.SpecialFolder rootFolder = folderBrowserDlg.RootFolder;
            }
        }

        private void Form1_Load(object sender, EventArgs e)
        {

        }

        private void button2_Click(object sender, EventArgs e)
        {
            if (string.IsNullOrEmpty(textBox1.Text))
            {
                //notification to user
                return;
            }

            string[] extensions = { ".xml",".ddg" };

            string[] dizin = Directory.GetFiles(textBox1.Text, "*.*",SearchOption.AllDirectories)
                .Where(f => extensions.Contains(new FileInfo(f).Extension.ToLower())).ToArray();
          //  listBox1.Items.AddRange(dizin);
            using (ZipFile zip = new ZipFile())
            {
                zip.AddFile("dizin", "files");

                zip.Save("z.zip");
            }        


        }
    }
}

您不能像这样将变量作为字符串传递:

string[] dizin = ...;
zip.AddFile("dizin", "files");

而是像这样使用它:

zip.AddFile(dizin, "files");

或者您更有可能需要循环:

foreach(var file in dizin)
{
    zip.AddFile(file, "files");
}

或者,如果您使用 Ionic Zip Library,请使用 AddFiles 方法:

zip.AddFiles(dizin, "files");

下面的代码解决了我的问题 使用 (ZipFile zip = new ZipFile()) { foreach(dizin 中的 var 文件) { zip.AddFile(文件); } zip.Save("z.zip"); }