如何传递使用 Web 客户端异步下载的对象?



我正在尝试异步下载 Json 类型的数据。 (我知道如何传递 uri,但不知道如何/在哪里下载它。

编辑,我在 .NET 3.5 上

在以下情况下如何执行此操作:

using (var client = new System.Net.WebClient())
var downloaded;
{
client.DownloadDataAsync(myUri, downloaded);
}
Console.WriteLine(downloaded);

如果您使用的是 .NET Framework 3.5,则此示例代码应该可以帮助您入门

static void Main(string[] args)
{
Uri myUri = new Uri("http://google.com");
using (System.Net.WebClient client = new System.Net.WebClient())
{
client.DownloadStringCompleted += Client_DownloadStringCompleted; 
// the WebClient is NOT thread safe so you cannot make concurrent calls
client.DownloadStringAsync(myUri);
// if you need to wait for the operation to finish
//while (client.IsBusy)
//{
//    System.Threading.Thread.Sleep(100);
//}
}
Console.WriteLine("Done");
Console.ReadLine();
}
private static void Client_DownloadStringCompleted(object sender, DownloadStringCompletedEventArgs e)
{
System.IO.File.WriteAllText(Path.GetTempFileName(), e.Result);
}

但是,如果您可以使用较新版本的.NET或.NET Core,我建议您使用HttpClient

using (var client = new System.Net.Http.HttpClient())
{
var response = await client.GetAsync(myUri);
var json = await response.Content.ReadAsStringAsync();
// to download as a byte array and save locally:
//      var bytes = await response.Content.ReadAsByteArrayAsync();
//      System.IO.File.WriteAllBytes("YourPath", bytes);
}

最新更新