Search code examples
c#ssis-2012.net-4.6.1

Follow up for Download a File in C# that website uses cookies


This is a follow up from Download a file but it seems like I have to do it with a browser.

I feel the question was answered but I need additional help.

Here is my current code:

    public async void TryDownload()
    {
        var clientHandler = new HttpClientHandler
        {
            AllowAutoRedirect = true,
            UseCookies = true,
            CookieContainer = new CookieContainer()
        };

        using (var httpClient = new HttpClient(clientHandler))
        {
            // this gets the request and allows the site to set cookies.
            var warmup = await httpClient.GetAsync("https://www.fapiis.gov/fapiis/allfapiisdata.action"); //This is the last line that runs when I step thru it.

            // get the file (cookies are sent automatically).
            var fileResponse = httpClient.GetAsync("https://www.fapiis.gov/fapiis/downloadview?type=allFapiis");

            if (fileResponse.Result.IsSuccessStatusCode)
            {
                HttpContent content = fileResponse.Result.Content;
                var contentStream = await content.ReadAsStreamAsync();

                string fname = "allFapiis" + DateTime.Now.ToLongDateString() + ".xlsx";
                using (var fileStream = System.IO.File.Create(@"C:\ERA\DATA\FAPIIS\" + fname))
                {
                    contentStream.CopyTo(fileStream);
                }
            }
        }
    }    

    public void Main()
    {
        // TODO: Add your code here

        TryDownload();

        Dts.TaskResult = (int)ScriptResults.Success;
    }

I am running this in a script task in SSIS.

When I step through it, the process abruptly ends with setting of "warmup".

I can see that the process worked for the answerer because I can see that his output matches what I have downloaded manually.

If I try to incorporate await in the TryDownload() call from main it barks about needing to be in a async task method which I can't do because this is in main.

What am I doing wrong here?

Thanks for your help!


Solution

  • TryDownload should be a Task. Then you can await it.

    public async Task TryDownload()
    
    public static async void Main()
    {
        await TryDownload();
    }