对RTF进行压缩、解压出错
因为richtextbox中的文本带有格式,有时候还带有图片,因些想先把rtf压缩后再存到mdb,之后再从mdb解压显示到richtextbox,但过程中解压报错(GZip 头中的幻数不正确。请确保正在传入 GZip 流),望易做图门解惑~
Dim zpied As String
zpied =GZipMe.CompressString(RichTextBox1.Rtf )
RichTextBox1.Rtf = GZipMe.DecompressString(zpied)'报错
Imports System
Imports System.IO
Imports System.IO.Compression
Public Class GZipMe
''' <summary>
''' 对字符串进行压缩
''' </summary>
''' <param name="str">待压缩的字符串</param>
''' <returns>压缩后的字符串</returns>
Public Shared Function CompressString(ByVal str As String) As String
Dim compressString1 As String = ""
Dim compressBeforeByte As Byte() = System.Text.Encoding.UTF8.GetBytes(str)
Dim compressAfterByte As Byte() = GZipMe.Compress(compressBeforeByte)
compressString1 = System.Text.Encoding.UTF8.GetString(compressAfterByte)
Return compressString1
End Function
''' <summary>
''' 对字符串进行解压缩
''' </summary>
''' <param name="str">待解压缩的字符串</param>
''' <returns>解压缩后的字符串</returns>
Public Shared Function DecompressString(ByVal str As String) As String
Dim compressString2 As String = ""
Dim compressBeforeByte As Byte() = System.Text.Encoding.UTF8.GetBytes(str)
Dim compressAfterByte As Byte() = GZipMe.Decompress(compressBeforeByte)
compressString2 = System.Text.Encoding.UTF8.GetString(compressAfterByte)
Return compressString2
End Function
''' <summary>
''' 对文件进行压缩
''' </summary>
''' <param name="sourceFile">待压缩的文件名</param>
''' <param name="destinationFile">压缩后的文件名</param>
Public Shared Sub CompressFile(ByVal sourceFile As String, ByVal destinationFile As String)
Throw New Exception("The method or operation is not implemented.")
End Sub
''' <summary>
''' 对byte数组进行压缩
''' </summary>
''' <param name="data">待压缩的byte数组</param>
''' <returns>压缩后的byte数组</returns>
Public Shared Function Compress(ByVal data As Byte()) As Byte()
Try
Dim ms As New MemoryStream()
Dim zip As New GZipStream(ms, CompressionMode.Compress, True)
zip.Write(data, 0, data.Length)
zip.Close()
Dim buffer As Byte() = New Byte(ms.Length - 1) {}
ms.Position = 0
ms.Read(buffer, 0, buffer.Length)
ms.Close()
Return buffer
Catch e As Exception
Throw New Exception(e.Message)
End Try
End Function
Public Shared Function Decompress(ByVal data As Byte()) As Byte()
Try
Dim ms As New MemoryStream(data)
Dim zip As New GZipStream(ms, CompressionMode.Decompress, True)
Dim msreader As New MemoryStream()
Dim buffer As Byte() = New Byte(4095) {}
While True
Dim reader As Integer = zip.Read(buffer, 0, buffer.Length)'报错
If reader <= 0 Then
Exit While
End If
msreader.Write(buffer, 0, reader)
End While
zip.Close()
ms.Close()
msreader.Position = 0
buffer = msreader.ToArray()
msreader.Close()
Return buffer
Catch e As Exception
Throw New Exception(e.Message)
End Try
End Function
End Class
--------------------编程问答--------------------
看不懂,不敢胡言乱语
补充:.NET技术 , VB.NET