Search code examples
c#file-iodotnetzip

What is the root directory OR how do I set the directory in DotNetZip


where does DotNetZip get it's root directory for saving. All the save examples don't show the directory.

My goal is to recurse a folder and subfolders. In each folder I want to zip all the files into one zip and delete the source files.

    private void CopyFolder(string srcPath, string dstPath)
    {
        if (!Directory.Exists(dstPath))
            Directory.CreateDirectory(dstPath);
        string[] files = Directory.GetFiles(srcPath);
        string msg;
        string zipFileName;
        using (ZipFile z = new ZipFile(Path.Combine(srcPath,String.Format("Archive{0:yyyyMMdd}.zip", DateTime.Now))))
        {
            z.ReadProgress += new EventHandler<ReadProgressEventArgs>(z_ReadProgress);
            foreach (string file in files)
            {
                FileInfo fi = new FileInfo(file);
                AddLog(String.Format("Adding {0}", file));
                z.AddFile(file);

            }
            //z.Save(Path.Combine(srcPath, String.Format("Archive{0:yyyyMMdd}.zip", DateTime.Now)));
            z.Save();
            if (deleteSource)
            {
                foreach (string file in files)
                {
                    File.Delete(file);
                }
            }

            zipFileName = z.Name;
        }
        if (!compressOnly)
            File.Copy(Path.Combine(srcPath,zipFileName), Path.Combine(dstPath, Path.GetFileName(zipFileName)));
        string[] folders = Directory.GetDirectories(sourcePath);
        foreach (string folder in folders)
        {
            string name = Path.GetFileName(folder);
            string dest = Path.Combine(dstPath, name);
            Console.WriteLine(ln);
            log.Add(ln);
            msg = String.Format("{3}{4}Start Copy: {0}{4}Directory: {1}{4}To: {2}", DateTime.Now.ToString("G"), name, dest, ln, Environment.NewLine);
            AddLog(msg);
            if (recurseFolders)
                CopyFolder(folder, dest);
            msg = String.Format("Copied Directory: {0}{4}To: {1}\nAt: {2}{3}", folder, dest, DateTime.Now.ToString("G"), Environment.NewLine);
            AddLog(msg);
        }
    }

Solution

  • It's a path relative to the current working directory, or an absolute path. This is basically standard procedure for paths.

    EDIT: The path you save to has nothing to do with directories inside the zip. Either:

    using(ZipFile f = new ZipFile("zip_dir/foo.zip"))
    {
           f.AddFile("foo.txt");
           f.Save();
    }
    

    or

    using(ZipFile f = new ZipFile())
    {
            f.AddFile("foo.txt");
            f.Save("zip_dir/foo.zip");
    }
    

    does the correct thing, namely create a zip file at ./zip_dir/foo.zip containing a single foo.txt file. Of course, you can create subdirectories in the zip, but it's a separate issue.