C# 如何在独立存储中保存来自web的图像?
在我的应用程序中,我有一个指向图像的URL列表。我需要做的是下载这些图片并将它们保存在独立的存储中 我已经拥有的:C# 如何在独立存储中保存来自web的图像?,c#,windows-phone-7,isolatedstorage,C#,Windows Phone 7,Isolatedstorage,在我的应用程序中,我有一个指向图像的URL列表。我需要做的是下载这些图片并将它们保存在独立的存储中 我已经拥有的: using (IsolatedStorageFile localFile = IsolatedStorageFile.GetUserStoreForApplication()) { ... foreach (var item in MyList) { Uri uri = new Uri(item.url, UriKind.Absolute); BitmapImag
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
文件中具有place-inside函数。我尝试过很多解决方案,其中的问题是“无效的跨线程访问”
如何使其工作?如果在非UI线程上创建
WriteableBitmap
,则会获得无效的跨线程访问。使用Dispatcher
,确保代码在主线程上运行:
Deployment.Current.Dispatcher.BeginInvoke(() =>
// ...
);
此问题的解决方案是:
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);
}
@马泰乌斯罗格尔斯基
您应该使用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;
}
现在你有了图像,你可以通过有效的检查保存到你的隔离存储中,无论你在哪里调用这个函数我从来没有在App.xaml.cs中放过任何代码,你使用MVVM吗?您可以将其放在视图模型或模型中吗?否则,您可以尝试使用“App.xaml.cs”中的全局函数,我在整个应用程序中使用该函数。Dispatcher在此文件中不适用于我。您不能在模型中声明它为静态吗?声明什么?你们所说的模型是什么意思?我已经试过了,但它抛出了“无效指针”异常。