Search code examples
c#gitlabzip.net-4.5

Convert a byte array which is a zip file back into a zip file


I am downloading a zip file that is stored in GitLab using below code:

   using (HttpClientHandler handler = new HttpClientHandler())
    {
        ServicePointManager.Expect100Continue = true;
        ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls12 | SecurityProtocolType.Ssl3;

        using (HttpClient client = new HttpClient(handler))
        {
            HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Get, "https://my.gitlab.space/api/v4/projects/100/packages/generic/mypackage/1.0.0.0/myZipFile.zip");

            request.Headers.Add("PRIVATE-TOKEN", "myTokenHere");

            HttpResponseMessage response = await client.SendAsync(request);
            response.EnsureSuccessStatusCode();
            string responseBody = await response.Content.ReadAsStringAsync();

            byte[] data = Encoding.UTF8.GetBytes(responseBody);
            File.WriteAllBytes(@"D:\myZipFile.zip", data);
        }
   }

This should be the equivalent to the following curl command:

curl --header "PRIVATE-TOKEN: myTokenHere" "https://my.gitlab.space/api/v4/projects/100/packages/generic/mypackage/1.0.0.0/myZipFile.zip" --output myZipFile.zip

Above code and also the curl command are working ok, except that i cannot convert the byte array data into a zip file in my local disk. By default, the byte array is already a zip file.

What am I doing wrong.


Solution

  • Use ReadAsByteArrayAsync instead of ReadAsStringAsync. You want to read the content directly as the file's bytes.

    byte[] data = await response.Content.ReadAsByteArrayAsync();