當響應完全加載時,它完全駐留在內存中。這導致您的OutOfMemoryException。解決方案是將響應直接「流」到獨立存儲中。
請注意,下面的解決方案目前的缺點是您正在失去下載進度信息。
public async void btnDownload2_Click()
{
try
{
var httpClient = new HttpClient();
var response = await httpClient.GetAsync(new Uri("http://somelink/video/nameOfFile.mp4"), HttpCompletionOption.ResponseHeadersRead);
response.EnsureSuccessStatusCode();
using(var isolatedStorageFile = IsolatedStorageFile.GetUserStoreForApplication())
{
bool checkQuotaIncrease = IncreaseIsolatedStorageSpace(e.Result.Length);
string VideoFile = "PlayFile.wmv";
using(var isolatedStorageFileStream = new IsolatedStorageFileStream(VideoFile, FileMode.Create, isolatedStorageFile))
{
using(var stm = await response.Content.ReadAsStreamAsync())
{
stm.CopyTo(isolatedStorageFileStream);
}
}
}
}
catch(Exception)
{
// TODO: add error handling
}
}
但HTTP客戶端僅適用於4.5+框架和Windows Phone 8 但我的應用程序需要在WP7 + – Cheese
所以正確的問題將被移植,我怎麼能實現直接保存到隔離來自WebClient或HTTP客戶端的存儲 – Cheese
WP7.5支持HttpClient。甚至包括異步/等待支持。看到這個頁面:http://blogs.msdn.com/b/bclteam/archive/2013/02/18/portable-httpclient-for-net-framework-and-windows-phone.aspx –