DownloadFileTaskAsync C#

时间:2013-09-05 06:52:35

标签: c# networking asynchronous webclient-download

我尝试创建一个小程序来下载给定链接的文件。

我遇到的问题如下......当我下载* .htm,* .txt等文件时没有问题,但是当我尝试获取更大的文件时,比如* .zip,* .bmp我的程序仅下载2kb-7kb之间。

我也尝试过使用localhost,因为我认为在某些网站上可能存在一些外部查询的安全限制,但它们是相同的。 [我知道我现在正在组织主文件中的代码的方式远非正确,但就像我说的,这只是一个测试]

我的代码:

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

任何帮助都将不胜感激。

1 个答案:

答案 0 :(得分:1)

您的代码始终会下载索引网页。

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");

适合我