如何传递使用 webclient 异步下载的对象?
How do I pass the object downloaded asynchronously using webclient?
我正在尝试异步下载 Json 类型的数据。
(我知道如何传递 uri,但不会 how/where 下载它。)
编辑,我使用的是 .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);
}
我正在尝试异步下载 Json 类型的数据。 (我知道如何传递 uri,但不会 how/where 下载它。)
编辑,我使用的是 .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);
}