2011-08-27 50 views
0

我正在使用Windows Phone SDK 7,並試圖實現圖像文件的下載。我不能使用標準的BitmapImage對象,因爲我的服務器使用表單身份驗證cookie,而據我所知,沒有辦法將瀏覽器控件或BitmapImage對象傳遞給cookie容器......(順便說一句,如果有方法要做到這一點,我想知道 - 它會使我的代碼更簡單!)。從Windows Phone7中的流讀取

無論如何,我想要做的應該是可能的 - 我得到一個響應流,現在我需要從它讀取圖像數據。

Howerver

​​

返回錯誤:

Specified argument was out of the range of valid values. 
    Parameter name: count 
     at MS.Internal.InternalNetworkStream.BeginRead(Byte[] buffer, Int32 offset, Int32 count,   AsyncCallback callback, Object state) 
     at TestCode.ItemViewModel.ReadImageByChunks() 
     at TestCode.ItemViewModel.ReadCallback(IAsyncResult ar) 
     at MS.Internal.InternalNetworkStream.StreamAsyncResult.Complete(Int32 bytesProcessed,   Boolean synchronously, Exception error) 
     at MS.Internal.InternalNetworkStream.ReadOperation(Object state) 
     at MS.Internal.InternalNetworkStream.BeginRead(Byte[] buffer, Int32 offset, Int32 count,   AsyncCallback callback, Object state) 
     at TestCode.ItemViewModel.ReadImageByChunks() 
     at TestCode.ItemViewModel.<>c__DisplayClassb.<LoadImageFromServer>b__a(IAsyncResult rspAR) 
     at System.Net.Browser.ClientHttpWebRequest.<>c__DisplayClassa.<InvokeGetResponseCallback>b__8(Object state2) 
     at System.Threading.ThreadPool.WorkItem.doWork(Object o) 
     at System.Threading.Timer.ring() 

這不通過代碼發生第一次(當clientData.Position == 0)。第二次通過它總是拋出(當clientData.Position == 4096)。

count is _buffer.Length。

private void ReadImageByChunks() 
    { 
     try 
     { 
      _clientData.BeginRead(_buffer, _currentPosition, _buffer.Length, new AsyncCallback(ReadCallback), null); 

     } 
     catch (Exception error) 
     { 
      int i = 1; 
     } 
    } 

    private void ReadCallback(IAsyncResult ar) 
    { 
     try 
     { 
      int bytesRead = _clientData.EndRead(ar); 

      if (bytesRead > 0) 
      { 
       _imageStream.Write(_buffer, _currentPosition, bytesRead); 
       _currentPosition = _currentPosition + bytesRead; 
      } 

      if (bytesRead == _buffer.Length) 
       ReadImageByChunks(); 
      else 
      { 
       //do stuff 
      } 
     } 
     catch (Exception error) 
     { 
      int i = 1; 
     } 
    } 

我已經重新編寫這些代碼幾次,現在根據我自己的直覺和代碼,我在網上(但沒有具體到Windows Phone 7)上找到。以上版本模仿this的帖子。但到目前爲止沒有運氣。任何幫助,將不勝感激。

回答

2

不要將索引傳遞到BeginRead,因爲它指向要開始寫入的緩衝區的索引。您目前正在向外界寫入緩衝區。

將_currentPosition替換爲0,它應該可以解決問題。事實上,你根本不需要跟蹤_currentPosition,因爲流保持自己的狀態。

+0

謝謝理查德 - 這解決了問題!不幸的是,我沒有要求投票的答案:(。 – 2011-08-29 04:51:25

+0

我雖然做 - 做! –

+0

@ user917153你張貼該評論作爲一個新的,匿名,用戶。如果你重新登錄作爲發佈的用戶問題(LWP),您可以將其標記爲「答案」。如果您使用與以前相同的計算機/瀏覽器,您仍然可以登錄。 –