问题
I am making a WP7 app which download all my twitter feed. In this I want to download all the profile images and store them locally and use them, so that they would be downloaded every time i open the app. Please suggest any of the methods to do so.
What I am doing: using a WebClient to download the image
public MainPage()
{
InitializeComponent();
WebClient client = new WebClient();
client.DownloadStringCompleted += new DownloadStringCompletedEventHandler(client_DownloadStringCompleted);
client.DownloadStringAsync(new Uri("http://www.libpng.org/pub/png/img_png/pnglogo-blk.jpg"));
}
and store it to a file.
void client_DownloadStringCompleted(object sender, DownloadStringCompletedEventArgs e)
{
using (IsolatedStorageFile myIsolatedStorage = IsolatedStorageFile.GetUserStoreForApplication())
{
if (myIsolatedStorage.FileExists(fileName1))
myIsolatedStorage.DeleteFile(fileName1);
var fileName1 = "Image.jpg";
using (var fileStream = new IsolatedStorageFileStream(fileName1, FileMode.Create, myIsolatedStorage))
{
using (var writer = new StreamWriter(fileStream))
{
var length = e.Result.Length;
writer.WriteLine(e.Result);
}
var fileStreamLength = fileStream.Length;
fileStream.Close();
}
}
Now I am trying to set the image to a BitMapImage
BitmapImage bi = new BitmapImage();
using (IsolatedStorageFile myIsolatedStorage = IsolatedStorageFile.GetUserStoreForApplication())
{
using (IsolatedStorageFileStream fileStream = myIsolatedStorage.OpenFile(fileName1, FileMode.Open, FileAccess.Read))
{
var fileStreamLength2 = fileStream.Length;
bi.SetSource(fileStream);
}
}
But I am not able to set source of the BitmapImage. It is throwing System.Exception and nothing specific. Am I doing it the right way? I mean the procedure.
EDIT Another observation is the fileStreamLength and fileStreamLength2 are different.
回答1:
You're not supposed to use DownloadString to download a binary file. Use OpenReadAsync instead, and save the binary array to the isolated storage.
DownloadString will try to convert your data to UTF-16 text, which of course can't be right when dealing with a picture.
来源:https://stackoverflow.com/questions/10319817/download-an-image-from-url-and-opening-it-in-an-image-control-in-wp7