skip to Main Content

Let me preface by stating that I’ somewhat new to dealing with zipping/unzipping/reading/reading files. That being said, I’m doing a PoC that will retrieve data via api and write the responses to a database. The response is a zip file and inside this zip is the json data I will be reading and writing to the database.

I’m having some trouble unzipping and reading the information. Please find the code below:

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
            }

Thanks

2

Answers


  1. You can convert body to a byte array and then unzip it using 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());
        }
    
    Login or Signup to reply.
  2. Assuming you actually have a .zip file, you don’t need a MemoryStream, you just need to pass the existing stream to 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
        }
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search