![](/img/trans.png)
[英]How to Unzip all .Zip file from Folder using C# 4.0 and without using any OpenSource Dll?
[英]Unzip .zip File without Writing to Disc from Response c#
讓我先聲明我對處理壓縮/解壓縮/讀取/讀取文件有點陌生。 話雖如此,我正在做一個 PoC,它將通過 api 檢索數據並將響應寫入數據庫。 響應是一個 zip 文件,在這個 zip 內部是 json 數據,我將讀取和寫入數據庫。
我在解壓縮和閱讀信息時遇到了一些麻煩。 請在下面找到代碼:
HttpClient client = new HttpClient();
HttpRequestMessage request = new HttpRequestMessage
{
Method = HttpMethod.Get,
RequestUri = new Uri(baseUrl),
Headers =
{
{ "X-API-TOKEN", apiKey },
},
};
using (var response = await client.SendAsync(request))
{
response.EnsureSuccessStatusCode();
var body = await response.Content.ReadAsStringAsync();
// here is where I am stuck - not sure how I would unzip and read the contents
}
謝謝
假設您實際上有一個.zip
文件,您不需要MemoryStream
,您只需將現有的 stream 傳遞給ZipArchive
static HttpClient client = new HttpClient(); // always keep static client
async Task GetZip()
{
using var request = new HttpRequestMessage(HttpMethod.Get, new Uri(baseUrl))
{
Headers = {
{ "X-API-TOKEN", apiKey },
},
};
using var response = await client.SendAsync(request, HttpCompletionOption.ResponseHeadersRead);
response.EnsureSuccessStatusCode();
using var stream = await response.Content.ReadAsStreamAsync();
await ProcessZip(stream);
}
async Task ProcessZip(Stream zipStream)
{
using var zip = new ZipArchive(zipStream, ZipArchiveMode.Read);
foreach (var file in zip.Entries)
{
using var entryStream = file.Open();
await ....; // do stuff here
}
}
您可以將body
轉換為byte
數組,然后使用MemoryStream
解壓縮。
byte[] bytes = Encoding.ASCII.GetBytes(body);
using (var mso = new MemoryStream(bytes)) {
using (var gs = new GZipStream(msi, CompressionMode.Decompress)) {
CopyTo(gs, mso);
}
return Encoding.UTF8.GetString(mso.ToArray());
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.