使用ZipFile压缩文件时出错

时间:2015-11-19 10:08:35

标签: c# zipfile

我正在使用Windows表单应用程序。在我的应用程序中,我使用FolderBrowserDialogtextbox1和两个按钮。在我的文本框中,我正在传递文件夹。从文件夹中,它将选择特定的文件类型。获得这样的文件类型后,我需要使用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");
            }        


        }
    }
}

2 个答案:

答案 0 :(得分:2)

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

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");

答案 1 :(得分:0)

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