简体   繁体   English

跟进下载 C# 中的文件,该网站使用 cookies

[英]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.我在 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.我可以看到该过程适用于回答者,因为我可以看到他的 output 与我手动下载的匹配。

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.如果我尝试将await合并到来自 main 的TryDownload()调用中,它会抱怨需要使用异步任务方法,因为这是在 main 中,所以我不能这样做。

What am I doing wrong here?我在这里做错了什么?

Thanks for your help!谢谢你的帮助!

TryDownload should be a Task . TryDownload应该是一个Task Then you can await it.然后你可以等待它。

public async Task TryDownload()

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM