I have created a web service that use MTOM for file transfer and also has a web extension for handling exceptions.They both seem to workindependentlybut when used together problems arise.

I noticed that MTOM closes the m_applicationStream before the AfterSerilize Process stage has been reach. A solution was to create an inherited Memory Stream that refused to called base close method, this way the m_applicationStream is still open and usable. This is the inherited MemoryStream. The close method isoverriddento prevent the base stream from being closed. It is also overloaded to provide a way of closing the base stream if required. Finally the base Dispose method is hidden, and a new version is provided that close the base stream before calling the disposemethodso that we can make sure everything is cleaned up.

Class ExtMemoryStream
    Inherits System.IO.MemoryStream

    ''' <summary>
    '''   Overriden close method.
    ''' </summary>
    ''' <remarks>Does nothing.</remarks>
    <Obsolete("This method does not close the stream.")> _
    Public Overloads Overrides Sub Close()
    End Sub

    ''' <summary>
    '''   Closes the current stream and releases any resources (such as sockets and
    '''   file handles) associated with the current stream.
    ''' </summary>
    ''' <param name="close">True if the Stream should be closed.</param>
    Public Overloads Sub Close(ByVal close As Boolean)
        If close Then
            MyBase.Close()
        End If
    End Sub

    ''' <summary>
    '''   Releases all resources used by the System.IO.Stream.
    ''' </summary>
    Public Shadows Sub Dispose()
        ' Close the stream, as the base Dispose cannot call Close anymore
        MyBase.Close()
        MyBase.Dispose()
    End Sub
End Class


Now I am getting the following message that I can't find anywhere and am not sure how to solve. Please help.

Exception Type: System.FormatException
Exception Message: WSE2202: The stream is not in a valid format.
Exception Source: Microsoft.Web.Services3