我正在編寫一個應用程序,它需要將非常大的文件(通常超過150MB)下載到機器中。我知道WebClient具有緩衝限制,可以用於我的情況。因此,我遵循使用HttpWebRequest的方式在此處編寫我的下載功能:http://dotnet.dzone.com/articles/2-things-you-should-consider?mz=27249-windowsphone7。以下是我的代碼:在Windows Phone 7中下載大文件時拋出ProtocolViolationException
private void _downloadBook(string _filePath)
{
Uri _fileUri = new Uri(_filePath);
//DownloadFileName = System.IO.Path.GetFileName(_fileUri.LocalPath);
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(_fileUri);
request.AllowReadStreamBuffering = false;
request.BeginGetRequestStream(new AsyncCallback(GetData), request);
}
private void GetData(IAsyncResult result)
{
HttpWebRequest request = (HttpWebRequest)result.AsyncState;
HttpWebResponse response = (HttpWebResponse)request.EndGetResponse(result);
Stream str = response.GetResponseStream();
byte[] data = new byte[16 * 1024];
int read;
long totalValue = response.ContentLength;
while ((read = str.Read(data, 0, data.Length)) > 0)
{
if (streamToWriteTo.Length != 0)
Debug.WriteLine((int)((streamToWriteTo.Length * 100)/totalValue));
streamToWriteTo.Write(data, 0, read);
}
streamToWriteTo.Close();
Debug.WriteLine("COMPLETED");
}
然而,投擲ProtocolViolationException和以下堆棧:
System.Net.ProtocolViolationException了未處理 消息= ProtocolViolationException 堆棧跟蹤: 在System.Net。 Browser.ClientHttpWebRequest.InternalBeginGetRequestStream(AsyncCallback callback,Object state) at System.Net.Browser.ClientHttpWebRequest.BeginGetRequestStream(AsyncCallback callback,Object state) at HHC_EbookReaderWP7.Co在System.Reflection.RuntimeMethodInfo.InternalInvoke(RuntimeMethodInfo rtmi,Object obj,BindingFlags invokeAttr,Binder聯編程序,Object參數,CultureInfo文化,布爾isBinderDefault,組件調用程序,布爾verifyAccess,StackCrawlMark & stackMark) 在System.Reflection.RuntimeMethodInfo.InternalInvoke(對象OBJ,的BindingFlags invokeAttr,粘結劑粘結劑,在System.Reflection.MethodBase.Invoke對象[]參數,CultureInfo的文化,StackCrawlMark & stackMark) (對象OBJ ,Object []參數) at System.Delegate.DynamicInvokeOne(Object [] args) at System.MulticastDelegate.DynamicInvokeImpl(Object [] args) 在System.Delegate.DynamicInvoke(對象[]參數) 在System.Windows.Threading.DispatcherOperation.Invoke() 在System.Windows.Threading.Dispatcher.Dispatch(的DispatcherPriority優先級) 在System.Windows.Threading.Dispatcher。 OnInvoke(Object context) at System.Windows.Hosting.CallbackCookie.Invoke(Object [] args) at System.Windows.Hosting.DelegateWrapper.InternalInvoke(Object [] args) at System.Windows.RuntimeHost.ManagedHost.InvokeDelegate (IntPtr的pHandle,的Int32 nParamCount,ScriptParam [] pParams,ScriptParam & pResult)
什麼錯我的代碼?還是我需要進一步呢?謝謝。
準確的行和消息將有所幫助 – adontz