Home > Mobile >  Can you download a file from an HttpContent stream from within a Windows Forms Application?
Can you download a file from an HttpContent stream from within a Windows Forms Application?

Time:10-22

I recently developed a .NET Web App that downloaded zip files from a certain, set location on our network. I did this by retrieving the content stream and then passing it back to the View by returning the File().

Code from the .NET Web App who's behavior I want to emulate:

public async Task<ActionResult> Download()
    {
        try
        {
            HttpContent content = plan.response.Content;
            var contentStream = await content.ReadAsStreamAsync(); // get the actual content stream

            if (plan.contentType.StartsWith("image") || plan.contentType.Contains("pdf"))
                return File(contentStream, plan.contentType);

            return File(contentStream, plan.contentType, plan.PlanFileName);
        }
        catch (Exception e)
        {
            return Json(new { success = false });
        }
    }

plan.response is constructed in a separate method then stored as a Session variable so that it is specific to the user then accessed here for download.

I am now working on a Windows Forms Application that needs to be able to access and download these files from the same location. I am able to retrieve the response content, but I do not know how to proceed in order to download the zip within a Windows Forms Application.

Is there a way, from receiving the content stream, that I can download this file using a similar method within a Windows Form App? It would be convenient as accessing the files initially requires logging in and authenticating the user and thus can not be accessed normally with just a filepath.

CodePudding user response:

Well, depending on what you're trying to accomplish, here's a pretty simplistic example of download a file from a URL and saving it locally:

        string href = "https://www.learningcontainer.com/wp-content/uploads/2020/05/sample-zip-file.zip";
        WebRequest request = WebRequest.Create(href);
        using (WebResponse response = request.GetResponse())
        {
            using (Stream dataStream = response.GetResponseStream())
            {
                Uri uri = new Uri(href);
                string fileName = Path.GetTempPath()   Path.GetFileName(uri.LocalPath);
                using (FileStream fs = new FileStream(fileName, FileMode.OpenOrCreate))
                {
                    dataStream.CopyTo(fs);
                }
            }
        }
  • Related