如何检查文件下载是否完整

时间:2014-04-20 23:36:11

标签: c#

我要做的是从网页下载文件。文件下载完成后,我会把它打印到屏幕上。

using HtmlAgilityPack;
using NAudio.Wave;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;

namespace ConsoleApplication25
{
class Program
{
    static void Main(string[] args)
    {

        Uri remoteUri = new Uri("http://soundcloud.com/dubstep/spag-heddy-the-master-vip/download");
        string fileName1 = "t", myStringWebResource = null;

        // Create a new WebClient instance.
        using (WebClient myWebClient = new WebClient())
        {
            myStringWebResource = remoteUri + fileName1;
            // Download the Web resource and save it into the current filesystem folder.
            myWebClient.DownloadStringCompleted += new DownloadStringCompletedEventHandler(Url1_DownloadStringCompleted);
            myWebClient.DownloadFileAsync(remoteUri, fileName1);

        }
}
public static void Url1_DownloadStringCompleted(object sender, DownloadStringCompletedEventArgs e)
    {
        if (e.Error != null)
            return;
        yes();
    }
    public static void yes()
    {
        Console.WriteLine("RRRR");
        Console.Read();
    }
}
}

我遇到问题的地方是myWebClient.DownloadFileAsync(remoteUri, fileName1);我不知道我应该在那里拥有什么,而不是那里有什么。我还确认myWebClient.DownloadFile有效。

1 个答案:

答案 0 :(得分:4)

当我对代码进行这些更改时工作:将输入字符串更改为URI,修复本地路径,使用正确的事件处理程序并最终执行Console.Read。我稍微缩短了代码,但你明白了这个想法:

static void Main(string[] args)
{
    using (WebClient myWebClient = new WebClient())
    {
        myWebClient.DownloadFileCompleted += DownloadCompleted;
        myWebClient.DownloadFileAsync(new Uri("http://someUrl"), @"e:\file.mp3");
    }

    Console.ReadLine();
}

public static void DownloadCompleted(object sender, AsyncCompletedEventArgs e)
{
    Console.WriteLine("Success");
}