一、简单下载方式使用WebClient

/// <summary>
/// 简单下载方式
/// 说明:对于大文件的下载,当前处理,会出现假死,长时间之后如果现在成功才相应
/// 不能用户断点处理
/// </summary>
public static void Test1()
{
    //string url = "http://www.imooc.com/video/11555";
    string url = "http://v2.mukewang.com/98672526-02b5-454c-b31e-d8526755b40b/L.mp4?auth_key=1474171330-0-0-8ff3fe3a33cfd257577dfa999e41530d";

    DateTime start = DateTime.Now;
    Uri uri = new Uri(url);
    string filename = uri.AbsolutePath.Substring(uri.AbsolutePath.LastIndexOf("/") + 1);
    filename = LocalPathHelper.CurrentSolution + "/data/" + filename;
    //指定url 下载文件
    WebClient client = new WebClient();
    client.DownloadFile(url, filename);
    Console.WriteLine("下载文件成功,用时:" + (DateTime.Now - start).TotalSeconds + "秒");
}

二、分块下载

/// <summary>
/// 分段下载文件
/// 读取速度和分块大小、网速有关
/// </summary>
public static void Test3()
{
    string url = "http://v2.mukewang.com/98672526-02b5-454c-b31e-d8526755b40b/L.mp4?auth_key=1474171330-0-0-8ff3fe3a33cfd257577dfa999e41530d";
    DateTime start = DateTime.Now;
    Uri uri = new Uri(url);
    string filename = uri.AbsolutePath.Substring(uri.AbsolutePath.LastIndexOf("/") + 1);
    filename = LocalPathHelper.CurrentSolution + "/data/" + filename;
    //指定url 下载文件
    HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(url);
    Stream stream = request.GetResponse().GetResponseStream();
    //创建写入流
    FileStream fs = new FileStream(filename, FileMode.Create, FileAccess.Write);
    byte[] bytes = new byte[1024 * 512];
    int readCount = 0;
    while (true)
    {
        readCount = stream.Read(bytes, 0, bytes.Length);
        if (readCount <= 0)
            break;
        fs.Write(bytes, 0, readCount);
        fs.Flush();
    }
    fs.Close();
    stream.Close();
    Console.WriteLine("下载文件成功,用时:" + (DateTime.Now - start).TotalSeconds + "秒");
}


更多:

C#下载实例

C#下载实例(三)-断点下载


本文转载:CSDN博客