简体   繁体   中英

C# Ionic.Zip ZIP file , Multi-level directory appears

Solution Directory

E:\WebSolution\GenerateFiles
 | NEW HOTEL-4-64-1379.pdf
 | NEW HOTEL-4-64-1379.xls

Correct

E:\WebSolution\GenerateFiles
 | NEW HOTEL-4-64-1379.pdf
 | NEW HOTEL-4-64-1379.xls
 | NEW HOTEL-4-64-1379.zip (Extract) 
                       | NEW HOTEL-4-64-1379.pdf
                       | NEW HOTEL-4-64-1379.xls

Wrong

E:\WebSolution\GenerateFiles
 | NEW HOTEL-4-64-1379.pdf
 | NEW HOTEL-4-64-1379.xls
 | NEW HOTEL-4-64-1379.zip (Extract) 
                   |WebSolution
                       |--|GenerateFiles
                       |--|--|NEW HOTEL-4-64-1379.pdf
                       |--|--|NEW HOTEL-4-64-1379.xls

======================================================

Code

public void Main(){

   string path=Server.MapPath("~/GenerateFiles"); 
   string zipPackageFileName=System.IO.Path.Combine(path,"NEW HOTEL-4-64-1379.zip");

   string[] arrFileName=new string[]{
        System.IO.Path.Combine(path,"NEW HOTEL-4-64-1379.pdf"),
    System.IO.Path.Combine(path,"NEW HOTEL-4-64-1379.pdf")
   };   

   CompressFilesToZip(arrFileName,zipPackageFileName);

}

using Ionic.Zip;
public void CompressFilesToZip(String[] arrFileName, string zipPackageFileName)
{
    try
    {
        using (ZipFile zip = new ZipFile())
        {
            zip.AddFiles(arrFileName);
            zip.Encryption = EncryptionAlgorithm.WinZipAes256;
            zip.CompressionLevel = Ionic.Zlib.CompressionLevel.BestCompression;
            zip.Password = PASSWORD_ATTACHMENT;
            zip.Save(zipPackageFileName);
        }
    }
    catch (Exception e)
    {
        throw e;
    }
}

Who can help me ? Thanks!

Looking at the documentation , I suspect you want to call

zip.AddFiles(arrFileName, false, "");

so that the directory hierarchy isn't preserved. It's possible that just

zip.AddFiles(arrFileName, "");

would work too; it's not entirely clear to me.

(Additionally, I'd strongly recommend that you get rid of the try / catch block in your method - it's worse than useless, as it just loses information. If an exception is thrown within any of the ZipFile methods, you'll lose the full stack trace due to the way you're rethrowing the exception.)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM