Wednesday, June 23, 2010

Convert MemoryStream to String and String to MemoryStream

These functions allow you to swap strings and memory streams back and forth.


Public Shared Function GetMemoryStreamFromString(ByVal s As String) As IO.MemoryStream
        If s Is Nothing OrElse s.Length = 0 Then
            Return Nothing
        End If

        Dim m As New IO.MemoryStream()
        Dim sw As New IO.StreamWriter(m)

        Return m
    End Function


    Public Shared Function GetStringFromMemoryStream(ByVal m As IO.MemoryStream) As String
        If m Is Nothing OrElse m.Length = 0 Then
            Return Nothing
        End If

        m.Position = 0
        Dim sr As New IO.StreamReader(m)
        Dim s As String = sr.ReadToEnd()
        Return s
    End Function

No comments: