[英]Create an archive inside of an archive in C# with ZipArchive class
As the title says, I am trying to create a zip inside of a zip. 如标题所示,我正在尝试在zip内创建一个zip。
I have a zip archive created at a variable called "TargetFilePath" 我在名为“ TargetFilePath”的变量处创建了一个zip存档。
var projectDirectoryPath = currentProjectViewModel.DirectoryPath;
ZipFile.CreateFromDirectory(projectDirectoryPath, TargetFilePath+@"/Project.zip");
The above will not work, I am assuming because the path c:\\test.zip\\project.zip is not a valid path. 我假设上面的方法不起作用,因为路径c:\\ test.zip \\ project.zip不是有效路径。
edit for clarity: i literally want to zip up some files and place that zip inside of another archive. 为了清楚起见,请进行编辑:我确实想压缩一些文件并将其压缩到另一个档案中。 It has to be using System.IO.Compression, no 3rd party methods.
它必须使用System.IO.Compression,没有任何第三方方法。
From my understanding you have to create a target address for the zip files, and,also from my experience, that target address cannot be an invalid path such as "c:\\test.zip\\project.zip" 根据我的理解,您必须为zip文件创建目标地址,并且根据我的经验,该目标地址也不能是无效路径,例如“ c:\\ test.zip \\ project.zip”
The easiest way is to create your zip file in a temporary file with the contents of your projectDirectoryPath
and once that is done you add that file to your target zip archive. 最简单的方法是使用
projectDirectoryPath
的内容在一个临时文件中创建zip文件,然后将其添加到目标zip存档中。
So basically something like this: 所以基本上是这样的:
var projectDirectoryPath = currentProjectViewModel.DirectoryPath;
var tempFile = Path.Combine(Path.GetTempPath(), Path.GetRandomFileName());
try
{
ZipFile.CreateFromDirectory(projectDirectoryPath, tempFile);
using (var archive = ZipFile.Open(TargetFilePath, ZipArchiveMode.Update))
{
archive.CreateEntryFromFile(tempFile, "Project.zip", CompressionLevel.NoCompression);
}
}
finally
{
System.IO.File.Delete(tempFile);
}
I suggest you use CompressionLevel.NoCompression
because the zip archive is already compressed and another layer of compression will add no value to it. 我建议您使用
CompressionLevel.NoCompression
因为zip存档已被压缩,而另一层压缩将不会为其添加任何值。 Using ZipArchiveMode.Update
when opening the archive is important so the zip file is actually altered. 打开存档时使用
ZipArchiveMode.Update
很重要,因此实际上是更改了zip文件。 The other values for this enumerator are used to create a new archive from scratch or to open it as read-only. 此枚举器的其他值用于从头开始创建新档案或将其以只读方式打开。
In the example I used the CreateEntryFromFile
function. 在示例中,我使用了
CreateEntryFromFile
函数。 It is a extension method so make sure you have the namespace in the using
declarations. 这是一种扩展方法,因此请确保您在
using
声明中具有名称空间。
It is possible to implement this in a way so no temporary file is required, but that requires a lot more code, as you have to create the new zip file yourself and write it directly to the stream you get when creating a new entry in the achive
. 可以以某种方式实施此操作,因此不需要临时文件,但这需要更多代码,因为您必须自己创建新的zip文件,并将其直接写到在目录中创建新条目时获得的流中。
achive
。 But for most cases the example I gave should do the job. 但是在大多数情况下,我给出的例子可以胜任。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.