简体   繁体   English

DownloadFileTaskAsync C#

[英]DownloadFileTaskAsync C#

I'm trying to create a small program to download files given a link. 我正在尝试创建一个小程序来下载给定链接的文件。

The problem I have is the following... when I download files like *.htm , *.txt there is no problem, but when I try to get a bigger file, like *.zip, *.bmp my program only downloads between 2kb-7kb. 我遇到的问题如下...当我下载* .htm,* .txt之类的文件时没有问题,但是当我尝试获取更大的文件(例如* .zip,*。bmp之类)时,我的程序仅在2kb-7kb。

I tried also using localhost, because I thought maybe there are some security restrictions for externals queries in some websites but it was the same. 我也尝试使用localhost,因为我认为某些网站上的外部查询可能存在一些安全限制,但这是相同的。 [I know the way I'm organizing now the code in the main file is far away from being the correct, but like I said, this is just a test] [我知道我现在在组织主文件中的代码的方式离正确的地方很远,但是就像我说的那样,这只是一个测试]

My code: 我的代码:

    static DateTime lastUpdate;
    static long lastBytes = 0;

    static void Main()
    {
        MyTask();

        Console.ReadKey();
    }

    async static Task MyTask()
    {
        var wc = new WebClient();

        wc.DownloadProgressChanged += (sender, args) =>
            {
                Console.WriteLine("{0} - {1} % complete", ProgressChanged(args.BytesReceived), args.ProgressPercentage);
            };

        Task.Delay(150000).ContinueWith(ant =>
            {
                wc.CancelAsync();
                Console.WriteLine("ABORTED!");
            });

        //http://windows.php.net/downloads/releases/php-5.5.3-nts-Win32-VC11-x86.zip
        //await wc.DownloadFileTaskAsync("http://localhost/", "w-brand.png");
        //await wc.DownloadFileTaskAsync("http://oreilly.com", "webpage.htm");
        await wc.DownloadFileTaskAsync("http://windows.php.net/downloads/releases/", "php-5.5.3-nts-Win32-VC11-x86.zip");
    }

    static long ProgressChanged(long bytes)
    {
        if (lastBytes == 0)
        {
            lastUpdate = DateTime.Now;
            lastBytes = bytes;
            return 0;
        }

        var now = DateTime.Now;
        var timeSpan = now - lastUpdate;
        var bytesChange = bytes - lastBytes;
        var bytesPerSecond = timeSpan.Seconds != 0 ? bytesChange / timeSpan.Seconds : 0;

        lastBytes = bytes;
        lastUpdate = now;

        return bytesPerSecond;
    }

Any help would be appreciated. 任何帮助,将不胜感激。

Your code always downloads the index web-page. 您的代码始终下载索引网页。

The first parameter of DownloadFileTaskAsync is the web url, the second the local path where to store the file. DownloadFileTaskAsync的第一个参数是Web URL,第二个参数是存储文件的本地路径。

wc.DownloadFileTaskAsync("http://windows.php.net/downloads/releases/php-5.5.3-nts-Win32-VC11-x86.zip", @"c:\php-5.5.3-nts-Win32-VC11-x86.zip");

works for me 为我工作

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

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