2012-04-25 27 views
2

我正在製作一個WP7應用程序,下載我的所有推特供稿。在這裏,我想下載所有的個人資料圖片並將其存儲在本地並使用它們,以便每次打開應用程序時都會下載它們。請建議任何方法來做到這一點。從url下載圖片並在wp7中的圖像控件中打開它

我在做什麼:使用Web客戶端下載圖像

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")); 
    } 

,並將其存儲到文件中。

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(); 
      } 
     } 

現在我試圖將圖像設置爲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); 
    } 
} 

但我不能夠設置BitmapImage的來源。它拋出System.Exception並沒有具體的東西。我是否正確地做這件事?我的意思是程序。

編輯另一種觀察是fileStreamLength和fileStreamLength2是不同的。

+1

它可能是與這裏相同的問題嗎? http://stackoverflow.com/questions/7428260/wp7-invalid-cross-thread-access-scheduledtaskagent/7428442#7428442 – thumbmunkeys 2012-04-25 16:55:30

+1

嘿謝謝你的答覆,但事實並非如此。我檢查了它。 – Prakash 2012-04-25 16:58:29

回答

3

你不應該使用DownloadString來下載二進制文件。改爲使用OpenReadAsync,並將二進制數組保存到隔離存儲中。

DownloadString會嘗試將您的數據轉換爲UTF-16文本,這在處理圖片時當然不會是正確的。

+0

謝謝,夥計。這非常有幫助。 – Prakash 2012-04-25 18:11:49