Reading from a stream in Windows Phone7
I am working with Windows Phone SDK 7 and am trying to implement the download of an image file. I cannot use the standard BitmapImage object because my server uses forms authentication cookies and I as far as I can tell, there is no way to pass the browser control or the BitmapImage object a cookie container... (btw. if there is a way to do that, I'd like to know as well - it will make my code much simpler!).
Regardless, what I am trying to do should be possible - I get a response stream and now I need to read the image data from it.
Howerver
_clientData.BeginRead(_buffer, _currentPosition, _buffer.Length, new AsyncCallback(ReadCallback), null);
Returns the error:
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()
This does not happen the first time through the code (when clientData.Position==0). The second time through it always is thrown (when 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;
}
}
I have re-written this code several times now based on my own intuition and on code I have found on the Internet (but n开发者_Python百科one specific to Windows Phone 7). The version above is modeled on this post. But no luck so far. Any help would be appreciated.
Don't pass an index into BeginRead, as it refers to the index of the buffer to start writing to. You're currently asking out to write to the buffer outsider its bounds.
Replace _currentPosition with 0 and it should fix the problem. In fact, you don't need to track _currentPosition at all, since streams keep their own state.
精彩评论