【问题标题】:Follow up for Download a File in C# that website uses cookies跟进在 C# 中下载该网站使用 cookie 的文件
【发布时间】:2019-09-26 13:25:42
【问题描述】:

这是Download a file but it seems like I have to do it with a browser 的后续报道。

我觉得问题已得到解答,但我需要更多帮助。

这是我当前的代码:

    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;
    }

我在 SSIS 的脚本任务中运行它。

当我逐步完成时,该过程突然以设置“预热”结束。

我可以看到该过程适用于回答者,因为我可以看到他的输出与我手动下载的匹配。

如果我尝试将 await 合并到来自 main 的 TryDownload() 调用中,它会抱怨需要使用异步任务方法,而我不能这样做,因为这是在 main 中。

我在这里做错了什么?

感谢您的帮助!

【问题讨论】:

  • 看看this
  • @Matt.G 你的链接和这条评论解决了它:这就是给我的。语言版本也可以在 Properties page > Build Tab > Advanced 中设置。将其设置为 7.1 解决了我的问题,即使我真的不明白我做了什么。

标签: c# ssis-2012 .net-4.6.1


【解决方案1】:

TryDownload 应该是Task。然后你就可以等待了。

public async Task TryDownload()

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

【讨论】:

猜你喜欢
  • 1970-01-01
  • 2017-08-27
  • 1970-01-01
  • 2023-03-05
  • 1970-01-01
  • 1970-01-01
  • 2011-01-06
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多