title: Streamed WCF service failing
body: <p>My wcf client gives me the following error when attempting to download a file from the service:
  <em>"An error occurred while receiving the HTTP response to <a href="http://mypc-pc/xmlLoadService/Service.svc" rel="nofollow noreferrer">http://mypc-pc/xmlLoadService/Service.svc</a>. This could be due to the service endpoint binding not using the HTTP protocol. This could also be due to an HTTP request context being aborted by the server (possibly due to the service shutting down). See server logs for more details."</em></p>
  
  <p>The code being executed is this:</p>
  
  <pre><code> System.IO.FileStream fs;
          try
          {
              fs = (System.IO.FileStream)client.Download(@"C:\UploadedFiles\Test.txt");
              byte[] arr = new byte[fs.Length];
              int read;
              do
              {
                  read = fs.Read(arr, 0, arr.Length);
  
              } while (read != arr.Length);
  
              Console.WriteLine(ASCIIEncoding.ASCII.GetString(arr));
              Console.ReadLine();
          }
  </code></pre>
  
  <p>This is my web.config config:</p>
  
  <pre><code>&lt;bindings&gt;
     &lt;basicHttpBinding&gt;
         &lt;binding name="basicHTTP" receiveTimeout="00:10:00" 
                  sendTimeout="00:03:00" closeTimeout="00:10:00" 
                  openTimeout="00:03:00" messageEncoding="Mtom" 
                  maxBufferSize="100000" maxReceivedMessageSize="100000" 
                  transferMode="Buffered"&gt;
         &lt;/binding&gt;
     &lt;/basicHttpBinding&gt;
  &lt;/bindings&gt;
  &lt;services&gt;
     &lt;service behaviorConfiguration="ServiceBehavior" name="Service"&gt;
         &lt;endpoint address="" binding="wsHttpBinding" contract="IService"&gt;
             &lt;identity&gt;
                 &lt;dns value="localhost" /&gt;
             &lt;/identity&gt;
         &lt;/endpoint&gt;
         &lt;endpoint address="mex" binding="mexHttpBinding" 
                   contract="IMetadataExchange" /&gt;
     &lt;/service&gt;
     &lt;service behaviorConfiguration="mexBehavior" 
              name="LoadXMLService.XMLOperations"&gt;
          &lt;endpoint address="" 
                    binding="basicHttpBinding" 
                    bindingConfiguration="basicHTTP" 
                    behaviorConfiguration="" 
                    contract="LoadXMLService.IxmlLoad" /&gt;
     &lt;/service&gt;
  &lt;/services&gt;
  </code></pre>
  
  <p>It fails where the 'download' function is being called on the server.  </p>
  
  <p>UPDATE: From what I understand from the trace log, the file is not being opened at the service end.  </p>
  
  <p>This is the code that is supposed to open the file, and it does not throw any exceptions when going through it step by step:</p>
  
  <pre><code>  public Stream Download( string path )
      {
          try
          {
              using (FileStream stream = new FileStream(path, FileMode.Open, FileAccess.Read))
              {
  
                  return stream;
              }
          }
          catch (Exception ex)
          {
              string error = ex.Message;
  
              return null;
          }
      }
  </code></pre>
  
  <p>The file is a text file with only one line inside it.  Here's the trace log:</p>
  
  <pre><code>&lt;E2ETraceEvent xmlns="http://schemas.microsoft.com/2004/06/E2ETraceEvent"&gt;
  &lt;System xmlns="http://schemas.microsoft.com/2004/06/windows/eventlog/system"&gt;
  &lt;EventID&gt;524340&lt;/EventID&gt;
  &lt;Type&gt;3&lt;/Type&gt;
  &lt;SubType Name="Error"&gt;0&lt;/SubType&gt;
  &lt;Level&gt;2&lt;/Level&gt;
  &lt;TimeCreated SystemTime="2009-10-04T15:20:22.7770000Z" /&gt;
  &lt;Source Name="System.ServiceModel" /&gt;
  &lt;Correlation ActivityID="{cb13d023-8122-4199-896c-78684b2461db}" /&gt;
  &lt;Execution ProcessName="WebDev.WebServer" ProcessID="8104" ThreadID="8" /&gt;
  &lt;Channel /&gt;
  &lt;Computer&gt;TONY-PC&lt;/Computer&gt;
  &lt;/System&gt;
  &lt;ApplicationData&gt;
  &lt;TraceData&gt;
  &lt;DataItem&gt;
  &lt;TraceRecord xmlns="http://schemas.microsoft.com/2004/10/E2ETraceEvent/TraceRecord" Severity="Error"&gt;
  &lt;TraceIdentifier&gt;http://msdn.microsoft.com/en-GB/library/System.ServiceModel.ServiceOperationExceptionOnReply.aspx&lt;/TraceIdentifier&gt;
  &lt;Description&gt;Replying to an operation threw a exception.&lt;/Description&gt;
  &lt;AppDomain&gt;b986c3da-11-128991431145070000&lt;/AppDomain&gt;
  &lt;Source&gt;System.ServiceModel.Dispatcher.ImmutableDispatchRuntime/48562646&lt;/Source&gt;
  &lt;Exception&gt;
  &lt;ExceptionType&gt;System.ObjectDisposedException, mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089&lt;/ExceptionType&gt;
  &lt;Message&gt;Cannot access a closed file.&lt;/Message&gt;
  &lt;StackTrace&gt;
  at System.IO.__Error.FileNotOpen()
  at System.IO.FileStream.Read(Byte[] array, Int32 offset, Int32 count)
  at System.Xml.XmlMtomWriter.WriteXOPBinaryParts()
  at System.Xml.XmlMtomWriter.WriteEndElement()
  at System.ServiceModel.Channels.Message.OnWriteMessage(XmlDictionaryWriter writer)
  at System.ServiceModel.Channels.Message.WriteMessage(XmlDictionaryWriter writer)
  at System.ServiceModel.Channels.MtomMessageEncoder.WriteMessage(Message message, Stream stream, String startInfo, String boundary, String startUri, Boolean writeMessageHeaders)
  at System.ServiceModel.Channels.MtomMessageEncoder.WriteMessage(Message message, Stream stream, String boundary)
  at System.ServiceModel.Channels.HttpOutput.WriteStreamedMessage(TimeSpan timeout)
  at System.ServiceModel.Channels.HttpOutput.Send(TimeSpan timeout)
  at System.ServiceModel.Channels.HttpRequestContext.OnReply(Message message, TimeSpan timeout)
  at System.ServiceModel.Activation.HostedHttpContext.OnReply(Message message, TimeSpan timeout)
  at System.ServiceModel.Channels.RequestContextBase.Reply(Message message, TimeSpan timeout)
  at System.ServiceModel.Channels.RequestContextBase.Reply(Message message)
  at System.ServiceModel.Dispatcher.ImmutableDispatchRuntime.Reply(MessageRpc&amp;amp; rpc)
  &lt;/StackTrace&gt;
  &lt;ExceptionString&gt;System.ObjectDisposedException: Cannot access a closed file.
     at System.IO.__Error.FileNotOpen()
     at System.IO.FileStream.Read(Byte[] array, Int32 offset, Int32 count)
     at System.Xml.XmlMtomWriter.WriteXOPBinaryParts()
     at System.Xml.XmlMtomWriter.WriteEndElement()
     at System.ServiceModel.Channels.Message.OnWriteMessage(XmlDictionaryWriter writer)
     at System.ServiceModel.Channels.Message.WriteMessage(XmlDictionaryWriter writer)
     at System.ServiceModel.Channels.MtomMessageEncoder.WriteMessage(Message message, Stream stream, String startInfo, String boundary, String startUri, Boolean writeMessageHeaders)
     at System.ServiceModel.Channels.MtomMessageEncoder.WriteMessage(Message message, Stream stream, String boundary)
     at System.ServiceModel.Channels.HttpOutput.WriteStreamedMessage(TimeSpan timeout)
     at System.ServiceModel.Channels.HttpOutput.Send(TimeSpan timeout)
     at System.ServiceModel.Channels.HttpRequestContext.OnReply(Message message, TimeSpan timeout)
     at System.ServiceModel.Activation.HostedHttpContext.OnReply(Message message, TimeSpan timeout)
     at System.ServiceModel.Channels.RequestContextBase.Reply(Message message, TimeSpan timeout)
     at System.ServiceModel.Channels.RequestContextBase.Reply(Message message)
     at System.ServiceModel.Dispatcher.ImmutableDispatchRuntime.Reply(MessageRpc&amp;amp; rpc)&lt;/ExceptionString&gt;
  &lt;/Exception&gt;
  &lt;/TraceRecord&gt;
  &lt;/DataItem&gt;
  &lt;/TraceData&gt;
  &lt;System.Diagnostics xmlns="http://schemas.microsoft.com/2004/08/System.Diagnostics"&gt;
  &lt;LogicalOperationStack&gt;&lt;/LogicalOperationStack&gt;
  &lt;Timestamp&gt;921505170062&lt;/Timestamp&gt;
  &lt;Callstack&gt;
  at System.Environment.GetStackTrace(Exception e, Boolean needFileInfo)
  at System.Environment.get_StackTrace()
  at System.Diagnostics.TraceEventCache.get_Callstack()
  at System.Diagnostics.XmlWriterTraceListener.WriteFooter(TraceEventCache eventCache)
  at System.Diagnostics.XmlWriterTraceListener.TraceData(TraceEventCache eventCache, String source, TraceEventType eventType, Int32 id, Object data)
  at System.Diagnostics.TraceSource.TraceData(TraceEventType eventType, Int32 id, Object data)
  at System.ServiceModel.Diagnostics.DiagnosticTrace.TraceEvent(TraceEventType type, TraceCode code, String description, TraceRecord trace, Exception exception, Object source)
  at System.ServiceModel.Diagnostics.TraceUtility.TraceEvent(TraceEventType severity, TraceCode traceCode, TraceRecord extendedData, Object source, Exception exception)
  at System.ServiceModel.Diagnostics.TraceUtility.TraceEvent(TraceEventType severity, TraceCode traceCode, Object source, Exception exception)
  at System.ServiceModel.Dispatcher.ImmutableDispatchRuntime.Reply(MessageRpc&amp; rpc)
  at System.ServiceModel.Dispatcher.ImmutableDispatchRuntime.ProcessMessageCleanup(MessageRpc&amp; rpc)
  at System.ServiceModel.Dispatcher.ImmutableDispatchRuntime.ProcessMessage5(MessageRpc&amp; rpc)
  at System.ServiceModel.Dispatcher.ImmutableDispatchRuntime.ProcessMessage4(MessageRpc&amp; rpc)
  at System.ServiceModel.Dispatcher.ImmutableDispatchRuntime.ProcessMessage3(MessageRpc&amp; rpc)
  at System.ServiceModel.Dispatcher.ImmutableDispatchRuntime.ProcessMessage2(MessageRpc&amp; rpc)
  at System.ServiceModel.Dispatcher.ImmutableDispatchRuntime.ProcessMessage1(MessageRpc&amp; rpc)
  at System.ServiceModel.Dispatcher.MessageRpc.Process(Boolean isOperationContextSet)
  at System.ServiceModel.Dispatcher.ImmutableDispatchRuntime.Dispatch(MessageRpc&amp; rpc, Boolean isOperationContextSet)
  at System.ServiceModel.Dispatcher.ChannelHandler.DispatchAndReleasePump(RequestContext request, Boolean cleanThread, OperationContext currentOperationContext)
  at System.ServiceModel.Dispatcher.ChannelHandler.HandleRequest(RequestContext request, OperationContext currentOperationContext)
  at System.ServiceModel.Dispatcher.ChannelHandler.AsyncMessagePump(IAsyncResult result)
  at System.ServiceModel.Dispatcher.ChannelHandler.OnAsyncReceiveComplete(IAsyncResult result)
  at System.ServiceModel.Diagnostics.Utility.AsyncThunk.UnhandledExceptionFrame(IAsyncResult result)
  at System.ServiceModel.AsyncResult.Complete(Boolean completedSynchronously)
  at System.ServiceModel.Channels.InputQueue`1.AsyncQueueReader.Set(Item item)
  at System.ServiceModel.Channels.InputQueue`1.EnqueueAndDispatch(Item item, Boolean canDispatchOnThisThread)
  at System.ServiceModel.Channels.InputQueue`1.EnqueueAndDispatch(T item, ItemDequeuedCallback dequeuedCallback, Boolean canDispatchOnThisThread)
  at System.ServiceModel.Channels.InputQueueChannel`1.EnqueueAndDispatch(TDisposable item, ItemDequeuedCallback dequeuedCallback, Boolean canDispatchOnThisThread)
  at System.ServiceModel.Channels.SingletonChannelAcceptor`3.Enqueue(QueueItemType item, ItemDequeuedCallback dequeuedCallback, Boolean canDispatchOnThisThread)
  at System.ServiceModel.Channels.HttpChannelListener.HttpContextReceived(HttpRequestContext context, ItemDequeuedCallback callback)
  at System.ServiceModel.Activation.HostedHttpTransportManager.HttpContextReceived(HostedHttpRequestAsyncResult result)
  at System.ServiceModel.Activation.HostedHttpRequestAsyncResult.HandleRequest()
  at System.ServiceModel.Activation.HostedHttpRequestAsyncResult.BeginRequest()
  at System.ServiceModel.Activation.HostedHttpRequestAsyncResult.OnBeginRequest(Object state)
  at System.ServiceModel.Channels.IOThreadScheduler.CriticalHelper.WorkItem.Invoke2()
  at System.ServiceModel.Channels.IOThreadScheduler.CriticalHelper.WorkItem.Invoke()
  at System.ServiceModel.Channels.IOThreadScheduler.CriticalHelper.ProcessCallbacks()
  at System.ServiceModel.Channels.IOThreadScheduler.CriticalHelper.CompletionCallback(Object state)
  at System.ServiceModel.Channels.IOThreadScheduler.CriticalHelper.ScheduledOverlapped.IOCallback(UInt32 errorCode, UInt32 numBytes, NativeOverlapped* nativeOverlapped)
  at System.ServiceModel.Diagnostics.Utility.IOCompletionThunk.UnhandledExceptionFrame(UInt32 error, UInt32 bytesRead, NativeOverlapped* nativeOverlapped)
  at System.Threading._IOCompletionCallback.PerformIOCompletionCallback(UInt32 errorCode, UInt32 numBytes, NativeOverlapped* pOVERLAP)
  &lt;/Callstack&gt;
  &lt;/System.Diagnostics&gt;
  &lt;/ApplicationData&gt;
  &lt;/E2ETraceEvent&gt;
  </code></pre>