C# 从包含zip的流中提取文件
我正在使用HttpClient请求从internet下载zip文件。 我想解压缩zip文件中包含的所有文件,而不将zip文件保存到磁盘。 目前,我可以下载zip文件并将其保存到磁盘,提取其内容,然后从磁盘删除zip文件。这很好。但是,我想优化流程。 我找到了一种直接从下载的zip流中提取内容的方法,但我必须指定文件名和扩展名。 我不知道如何提取内容,同时保留其原始文件名和扩展名,而不指定它们 目前的做法:C# 从包含zip的流中提取文件,c#,.net,.net-core,C#,.net,.net Core,我正在使用HttpClient请求从internet下载zip文件。 我想解压缩zip文件中包含的所有文件,而不将zip文件保存到磁盘。 目前,我可以下载zip文件并将其保存到磁盘,提取其内容,然后从磁盘删除zip文件。这很好。但是,我想优化流程。 我找到了一种直接从下载的zip流中提取内容的方法,但我必须指定文件名和扩展名。 我不知道如何提取内容,同时保留其原始文件名和扩展名,而不指定它们 目前的做法: string requestUri = "https://www.nuget.org/ap
string requestUri = "https://www.nuget.org/api/v2/package/" + PackageName + "/" + PackageVersion;
HttpResponseMessage response = await client.GetAsync(requestUri);
response.EnsureSuccessStatusCode();
using Stream PackageStream = await response.Content.ReadAsStreamAsync();
SaveStream($"{DownloadPath}.zip", PackageStream);
ZipFile.ExtractToDirectory($"{DownloadPath}.zip", ExtractPath);
File.Delete($"{DownloadPath}.zip");
// Directly extract Zip contents without saving file and without losing filename and extension
using (ZipArchive archive = new ZipArchive(await response.Content.ReadAsStreamAsync()))
{
foreach (ZipArchiveEntry entry in archive.Entries)
{
using (Stream stream = entry.Open())
{
using (FileStream file = new FileStream("file.txt", FileMode.Create, FileAccess.Write))
{
stream.CopyTo(file);
}
}
}
}
.NET 4.8.NET核心3.1
C#8.0 在此方面的任何帮助都将不胜感激。
请随时评论其他方法或建议。
提前感谢。
ZipArchiveEntry
具有名称
和全名
属性,可用于获取存档中的文件名,同时保留其原始文件名和扩展名
FullName属性包含zip存档中条目的相对路径,包括子目录层次结构。(相反,“名称”属性仅包含条目的名称,不包含子目录层次结构。)
比如说
using (ZipArchive archive = new ZipArchive(await response.Content.ReadAsStreamAsync())) {
foreach (ZipArchiveEntry entry in archive.Entries) {
using (Stream stream = entry.Open()) {
string destination = Path.GetFullPath(Path.Combine(downloadPath, entry.FullName));
var directory = Path.GetDirectoryName(destination);
if (!Directory.Exists(directory))
Directory.CreateDirectory(directory);
using (FileStream file = new FileStream(destination, FileMode.Create, FileAccess.Write)) {
await stream.CopyToAsync(file);
}
}
}
}
将在存档中存储的相同子目录层次结构中提取文件,而如果使用了
entry.Name
,则所有文件将提取到相同的位置。如果目录不存在,如何创建目录?尝试使用Directory.CreateDirectory(downloadPath),但很多时候它会抛出DirectoryNotFoundException,即使该目录是在文件中创建的system@RonakThakkar检查更新,包括在尝试保存文件之前检查目录。