在我的应用程序中,我有图片的网址列表。我需要做的是下载这些图像并将它们保存在独立存储中。
我已经拥有的东西:
using (IsolatedStorageFile localFile = IsolatedStorageFile.GetUserStoreForApplication()) {
...
foreach (var item in MyList)
{
Uri uri = new Uri(item.url, UriKind.Absolute);
BitmapImage bitmap = new BitmapImage(uri);
WriteableBitmap wb = new WriteableBitmap(bitmap);
using (IsolatedStorageFileStream fs = localFile.CreateFile(GetFileName(item.url)))//escape file name
{
wb.SaveJpeg(fs, wb.PixelWidth, wb.PixelHeight, 0, 85);
}
}
...
}
此代码在我的App.xaml.cs
文件中包含函数。我尝试了很多解决方案,在这一个问题是“无效的跨线程访问”。
我怎样才能让它发挥作用?
答案 0 :(得分:0)
如果在非UI线程上创建WriteableBitmap
,则会获得无效的跨线程访问权限。确保使用Dispatcher
:
Deployment.Current.Dispatcher.BeginInvoke(() =>
// ...
);
答案 1 :(得分:0)
解决此问题的方法是:
foreach (var item in MyList)
{
Uri uri = new Uri(item.url, UriKind.Absolute);
HttpWebRequest request = HttpWebRequest.Create(uri) as HttpWebRequest;
request.BeginGetResponse((ar) =>
{
var response = request.EndGetResponse(ar);
Deployment.Current.Dispatcher.BeginInvoke(() =>
{
using (var stream = response.GetResponseStream())
{
var name = GetFileName(item.url);
if (localFile.FileExists(name))
{
localFile.DeleteFile(name);
}
using (IsolatedStorageFileStream fs = localFile.CreateFile(name))
{
stream.CopyTo(fs);
}
}
});
}, null);
}
答案 2 :(得分:0)
@Mateusz Rogulski
您应该使用WebClient,我建议您按照解决方案解决问题。试试吧。
public string YourMethod(string yoursUri)
{
BitmapImage image=new BitmapImage();
WebClient client = new WebClient();
client.OpenReadCompleted += async (o, args) =>
{
Stream stream = new MemoryStream();
await args.Result.CopyToAsync(stream);
image.SetSource(stream);
};
client.OpenReadAsync(new Uri(yoursUri));//if passing object than you can write myObj.yoursUri
return image;
}
现在你有了图片,无论你在哪里调用这个函数,你都可以通过有效的检查保存到你的isolatedStorage中