How do I use GZipStream with System.IO.MemoryStream?

前端 未结 9 1002
遥遥无期
遥遥无期 2020-12-04 16:36

I am having an issue with this test function where I take an in memory string, compress it, and decompress it. The compression works great, but I can\'t seem to get the dec

9条回答
  •  半阙折子戏
    2020-12-04 17:08

    Another implementation, in VB.NET:

    Imports System.Runtime.CompilerServices
    Imports System.IO
    Imports System.IO.Compression
    
    Public Module Compressor
    
         _
        Function CompressASCII(str As String) As Byte()
    
            Dim bytes As Byte() = Encoding.ASCII.GetBytes(str)
    
            Using ms As New MemoryStream
    
                Using gzStream As New GZipStream(ms, CompressionMode.Compress)
    
                    gzStream.Write(bytes, 0, bytes.Length)
    
                End Using
    
                Return ms.ToArray
    
            End Using
    
        End Function
    
         _
        Function DecompressASCII(compressedString As Byte()) As String
    
            Using ms As New MemoryStream(compressedString)
    
                Using gzStream As New GZipStream(ms, CompressionMode.Decompress)
    
                    Using sr As New StreamReader(gzStream, Encoding.ASCII)
    
                        Return sr.ReadToEnd
    
                    End Using
    
                End Using
    
            End Using
    
        End Function
    
        Sub TestCompression()
    
            Dim input As String = "fh3o047gh"
    
            Dim compressed As Byte() = input.CompressASCII()
    
            Dim decompressed As String = compressed.DecompressASCII()
    
            If input <> decompressed Then
                Throw New ApplicationException("failure!")
            End If
    
        End Sub
    
    End Module
    

提交回复
热议问题