将目录添加到现有的.zip文件 [英] Adding a directory to an existing .zip file
问题描述
首先,我想说的是,我一直在寻找解决方案,但没有找到不需要解压缩的地方,请添加我的文件夹,然后再次进行压缩。我没有使用任何第三方库。如果可能的话,我想使用system.io.compression来执行此操作。...否则,我将dotnetzip作为我的最后选择。
First of all I would like to say that i've tried looking for the solution to this and I haven't found one where I don't have to unzip, add my folder and then zip again. I am not using any third party libraries. I would like to do this using system.io.compression if it's possible at all ... If not I would use dotnetzip as my last resort.
TL; DR。
我希望能够将包含文件的目录添加到已创建的zip文件中。是否可以使用 System.Io.Compression
库?
TL;DR.
I want to be able to add directories with files in them to an already created zip file. Is this possible using the System.Io.Compression
library ?
EDIT :
using (FileStream zipToOpen = new FileStream(zipfile, FileMode.Open))
{
using (ZipArchive archive = new ZipArchive(zipToOpen, ZipArchiveMode.Update))
{
ZipArchiveEntry readmeEntry = archive.CreateEntry("testFolder/");
}
}
因此,使用此代码,我可以在其中创建文件夹将没有任何文件。现在的问题是我是否必须再次运行此代码,以将每个文件从源文件夹获取到zip内的该文件夹,还是有更好的方法?
So, using this code I am able to create a folder inside but it will be without any files in it. My question now is do I have to run this code again to get every file from my source folder to this folder inside the zip or is there a better way?
推荐答案
感谢@stuartd,我设法找到了一种方法。他为我指出了这个答案 https://stackoverflow.com/a/22339337/3182972 ,我找到了一种实现方法
I managed to find a way to do this thanks to @stuartd. He pointed me to this answer https://stackoverflow.com/a/22339337/3182972 and I found a way to implement it into my code that creates directories with files inside them from a source location of said directories.
这是代码:
using (FileStream zipToOpen = new FileStream("c:\MyDestination\test.zip", FileMode.Open))
{
using (ZipArchive archive = new ZipArchive(zipToOpen, ZipArchiveMode.Update))
{
ZipArchiveEntry readmeEntry;
DirectoryInfo d = new DirectoryInfo(c:\MySourceFolder);
FileInfo[] Files = d.GetFiles("*");
foreach (FileInfo file in Files)
{
readmeEntry = archive.CreateEntryFromFile("c:\MySourceFolder"+ "\\" + file.Name, "MySourceFolder" + "/" + file.Name);
}
}
}
所以我所做的就是去到我的源目录,并遍历所有文件,并以一个foreach周期将它们添加到zip文件的目标文件夹中。
So what I did was go to my source directory and went through all of the files that are there and with a foreach cycle I added them to the destination folder in the zip file.
您还可以获取带有以下代码的源目录名称:
You can also get the source directory name with this code:
string sourcepath = "C:\MySourceFolder";
int ind = sourcepath.LastIndexOf("\\") + 1;
string folderName = sourcepath.Substring(ind, folder.Length - ind);
这篇关于将目录添加到现有的.zip文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!