压缩文件时出现 BadDirectoryException

BadDirectoryException when zipping files

我尝试将所有文​​件压缩到一个文件夹中,然后将它们保存到另一个文件夹中。

错误:

That name specifies an existing directory. Please specify a filename. Parameter Name: fileName

AppConfig:

<appSettings>
    <add key="ZipLocation" value="c:\example\start"/>
    <add key="ZipSaveLocation" value="c:\example\extract"/>
</appSettings>

代码:

//using Ionic.Zip;

static void Main(string[] args)
{
    string startPath = ConfigurationManager.AppSettings["ZipLocation"].ToString();
    string zipPath = ConfigurationManager.AppSettings["ZipSaveLocation"].ToString();
    int key = Convert.ToInt32(Console.ReadLine());
    try
    {
        using (ZipFile zip = new ZipFile())
        {
            String[] filenames = System.IO.Directory.GetFiles(startPath);

            foreach (String filename in filenames)
            {
                Console.WriteLine("Adding {0}...", filename);
                ZipEntry e = zip.AddFile(filename);
                e.Comment = "bla bla."; 
            }
            zip.Comment = String.Format("This zip archive was created by the CreateZip example application on machine '{0}'", System.Net.Dns.GetHostName());
            zip.Save(zipPath);
        }
    }
    catch (Exception)
    {
        throw;
    }
}

你有这个:

string zipPath = ConfigurationManager.AppSettings["ZipSaveLocation"].ToString();

然后你称之为:

zip.Save(zipPath);

zipPath 不是一个文件,它是一个文件夹。

通过执行以下操作来修复您的代码:

zip.Save(Path.Combine(zipPath,"newZipFile.zip"));

您必须提供文件而不仅仅是路径:

只需将 c:\example\extract 更改为 c:\example\extract\extract.zip 例如。

编辑:

使用以下内容:

zip.Save(Path.Combine(zipPath, Path.GetDirectoryName(startPath)));