How to zip selected files? not all the files in a

2019-09-01 05:28发布

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?

3条回答
爱情/是我丢掉的垃圾
2楼-- · 2019-09-01 05:59

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

查看更多
姐就是有狂的资本
3楼-- · 2019-09-01 06:05

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.

查看更多
狗以群分
4楼-- · 2019-09-01 06:11

I would recommend using File.Copy to copy all your desired files to a temporary directory, then zip them all from there and delete the temporary directory once the zip operation has finished.

查看更多
登录 后发表回答