我正在使用Windows Phone SDK 7,我正在尝试实现图像文件的下载。我不能使用标准的BitmapImage对象,因为我的服务器使用表单身份验证cookie,据我所知,没有办法将浏览器控件或BitmapImage对象传递给cookie容器......(顺便说一句,如果有办法的话)要做到这一点,我也想知道 - 这将使我的代码更简单!)。
无论如何,我想做的事情应该是可能的 - 我得到一个响应流,现在我需要从中读取图像数据。
Howerver
_clientData.BeginRead(_buffer, _currentPosition, _buffer.Length, new AsyncCallback(ReadCallback), null);
返回错误:
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是_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帖子上建模的。但到目前为止没有运气。任何帮助,将不胜感激。
答案 0 :(得分:2)
不要将索引传递给BeginRead,因为它引用了 buffer 的索引来开始写入。你现在要求在缓冲区外写入它的边界。
将_currentPosition替换为0,它应该解决问题。实际上,您根本不需要跟踪_currentPosition,因为流保持自己的状态。