BadDirectoryException when zipping files

677 views Asked by At

I tried zip all files in a folder, and save them to another folder.

Error:

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>

Code:

//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;
    }
}
2

There are 2 answers

2
bill On BEST ANSWER

You have this:

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

and then you call this:

zip.Save(zipPath);

zipPath is not a file, it's a folder.

Fix your code by doing something like:

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

You have to provide a file not just a path:

just change c:\example\extract to c:\example\extract\extract.zip for example.

Edit:

Use the following:

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