Search code examples
c#windowszip

How to save Zip file on local machine which is coming from HttpClient using SaveFileDialog in Windows application using C#?


I want to store the zip file which is retrieved by the ToRetrieve method and store it on the local machine using SaveFileDialog controller in a Windows application writtein in C#.

This is my code:

if (!string.IsNullOrEmpty(FileName))
{
    APIOrderMethods objAPIOrderMethods = new APIOrderMethods();
    saveFileDialog1.Filter = "zip files (*.zip)|*.zip|All files (*.*)|*.*";
    saveFileDialog1.Title = FileName;

    if (saveFileDialog1.ShowDialog() == DialogResult.OK) 
    {
        Stream stream = objAPIOrderMethods.ToRetrieve(FileName, ServicelURL, useName, password);
        Stream streamToWriteTo = File.Open(saveFileDialog1.FileName, FileMode.Create, FileAccess.ReadWrite);
        stream.CopyToAsync(streamToWriteTo);
    } 
               
    label12.ForeColor = Color.Green;
}

But I get this error:

Exception :'Cannot access a closed Stream.'

ToRetrieve method for getting the Zip file:

public  Stream ToRetrieve(string Filename, string serviceURL, string Username, string Password)
{
    Stream Result = null;
    var _saveDir = System.Configuration.ConfigurationManager.AppSettings["Save"];

    try
    {
        using (HttpClient client = new HttpClient())
        {
            string url = "https://codeload.github.com/tugberkugurlu/ASPNETWebAPISamples/zip/master";

            using (HttpResponseMessage response =  client.GetAsync(url, HttpCompletionOption.ResponseHeadersRead).Result)
            using (Stream streamToReadFrom =  response.Content.ReadAsStreamAsync().Result)
            {
                Result = streamToReadFrom;
            }
        }
    }
    catch (Exception ex)    
    {
        throw;
    }

    return Result;
}

Solution

  • The problem lies in the method, ToRetrieve.

    With streamToReadFrom being in a using statement, the Dispose method will be called.

    Since result contains the reference, you are returning a closed stream.