我的Listbox已经包含这样的链接:http://example.com/sorted/Avicii/Avicii+-+Wake+Me+Up.mp3我想在同一时间下载所有建议吗? 这段代码我用来下载单个文件
private void txtUrl_TextChanged(object sender, EventArgs e)
{
try
{
// function that enter the file name automatically in the savefiledialog.
Uri uri = new Uri(txtUrl.Text);
// Save the file name to the string.
filename = Path.GetFileName(uri.LocalPath);
}
catch
{
// no need need an exception message.
}
}
private void DownloadFile(string url, string save)
{
using (var client = new WebClient())
{
// Run code every time the download changes.
client.DownloadProgressChanged += new DownloadProgressChangedEventHandler(Changed);
// Run codes when file download has been completed.
client.DownloadFileCompleted += new AsyncCompletedEventHandler(Completed);
client.DownloadFileAsync(new Uri(url), save);
答案 0 :(得分:1)
解决方案可能如下所示:
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
namespace SillyCSharpNameSpace
{
public class VerboseDownloaderClassName
{
private string downloadFile(string url, string localDir)
{
try
{
var localPath = Path.Combine(localDir, Path.GetFileName(url));
using (var wc = new WebClient())
{
wc.DownloadFile(url, localPath);
return localPath;
}
}
catch (Exception e)
{
Console.WriteLine(e);
return null;
}
}
public void DownloadAll(List<string> urls)
{
urls.AsParallel()
.Where(url => !string.IsNullOrWhiteSpace(url))
.WithDegreeOfParallelism(20)
.Select(url => downloadFile(url, "."));
}
}
}
我确定如果你使用WinForms或ASP.NET,你可以弄清楚如何从列表框项中获取url字符串。请注意,Path.GetFileName()仅适用于您提供的表单 - URL末尾的文件名,没有任何URL参数。 AsParallel
方法将下载工作并行化为20&#34;线程&#34;。我认为它应该足以达到你的目的。
奖金。这与F#相同,只是因为我可以; o)
open System.IO
open System.Net
open FSharp.Collections.ParallelSeq // from NuGet FSharp.Collections.ParallelSeq
let downloadFile dir url =
let localPath = Path.Combine(dir, Path.GetFileName url)
try
use wc = new WebClient()
wc.DownloadFile(url, localPath)
Some localPath
with ex ->
printfn "Can't download file from %s: %A" url ex
None
let downloadAll (urls: string list) =
urls
|> PSeq.withDegreeOfParallelism 20 // 20 threads
|> PSeq.choose (downloadFile ".")