简体   繁体   中英

How to zip selected files? not all the files in a directory in c#

I want to zip some files in a directory. I have googled a lot but i always saw examples about zipping a directory (all files in directory) by the code below:

string startPath = @subPath;

string zipPath = @"C:\result.zip";

ZipFile.CreateFromDirectory(startPath, zipPath);

I am referencing System.IO.Compression.Filesystem.dll

This code zips all the files in the directory referenced by startPath.

I tried ZipArchive class for compressing but it compress file with directories on its path. For example, assume i want to zip "a.txt" located at "C:\\directories\\Graphics\\a.txt". The zip file contains directories "directories" and "Graphics" and into these directories the file "a.txt". It is not a good solution to cut files then erase the directories and paste again since i am working on big size data.

How can I zip only some of files at a directory?

How can I zip some files that are located in different directories?

I am looking up the subject for 2 days. Is it a kind of constraint in .Net?

You can use the ZipArchive class, first create it and then - once created you just add ZipArchiveEntry objects into the archive. Each of the ZipArchiveEntry objects represents a single file that you will add to the archive.

Some tips: You can find more info and a sample of how this could be done on MSDN, here: http://msdn.microsoft.com/pl-pl/library/system.io.compression.ziparchive(v=vs.110).aspx and here: http://msdn.microsoft.com/pl-pl/library/system.io.compression.ziparchiveentry(v=vs.110).aspx .

This may not be an exact solution but should work for your scenario. I'll give you the steps :

  1. Create a Temporary Directory

  2. Read and copy your Selected files into the Temporary directory. This applies to your second scenario as well.

  3. Zip the temporary directory

  4. Delete Temporary Directory after you are done

我建议使用File.Copy将所有需要的文件复制到一个临时目录,然后从那里压缩所有文件,并在zip操作完成后删除该临时目录。

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