gZipBuffer DECompression从C#转换为F#

时间:2012-09-21 18:46:49

标签: f#

Hy Guys,所以在你帮我正确转换“压缩”功能之后,我试着转换了解压缩功能

现在我在这里 (我的解压缩功能)

let DecompressString (detext : string) =
    let buffer = Convert.FromBase64String detext
    using (new MemoryStream ()) <| fun memoryStream ->
            using (new GZipStream(memoryStream, CompressionMode.Decompress, true)) <| fun gzipStream ->
            memoryStream.Position <- 0L
            memoryStream.Read(buffer, 0, Array.length buffer)
            Encoding.UTF8.GetString(buffer)

原始的Compressfunction是

let compressString (text : string) =
let buffer = Encoding.UTF8.GetBytes text
using (new MemoryStream ()) <| fun memoryStream ->
    using (new GZipStream(memoryStream, CompressionMode.Compress, true)) <| fun gzipStream ->
        gzipStream.Write (buffer, 0, Array.length buffer)
    memoryStream.Position <- 0L
    let compressedData = Array.zeroCreate (int memoryStream.Length)
    memoryStream.Read (compressedData, 0, compressedData.Length)
    let gzipBuffer = Array.zeroCreate (compressedData.Length + 4)
    Buffer.BlockCopy (compressedData, 0, gzipBuffer, 4, compressedData.Length)
    Buffer.BlockCopy (BitConverter.GetBytes buffer.Length, 0, gzipBuffer, 0, 4)
    Convert.ToBase64String gzipBuffer

如果我压缩像这样的字符串

File.WriteAllText("test",compressString("bla"))

(我在此文件中保存名为“test”的文件是来自“bla”的压缩字符串)

AwAAAB+LCAAAAAAABADtvQdgHEmWJSYvbcp7f0r1StfgdKEIgGATJNiQQBDswYjN5pLsHWlHIymrKoHKZVZlXWYWQMztnbz33nvvvffee++997o7nU4n99//P1xmZAFs9s5K2smeIYCqyB8/fnwfPyImZfb/ADmz70cDAAAA”&lt;对我来说似乎比以前更大? :d

好吧现在我尝试再次解压缩,如:

File.WriteAllText("test2",DecompressString(File.ReadAllText("test")))

但是在新的“test2”文件中只有不可读的文本,如:

?"&e�ï¿

所以我认为我的dcompress功能无法正常工作。

也许你的英雄可以帮助我第二次也是最后一次? :) 无论如何,提前谢谢

1 个答案:

答案 0 :(得分:1)

首先,您正在读取的内存流为空,因此不会将任何内容写入目标缓冲区。

其次,您重新使用buffer,其中包含基本64字符串参数的字节。

您无法获得GZipStream的长度,因此您必须将其复制到另一个内存流:

let DecompressString (detext : string) =
    let buffer = Convert.FromBase64String detext
    using (new MemoryStream ()) <| fun memoryStream ->
        memoryStream.Write(buffer, 0, Array.length buffer)
        memoryStream.Seek(0L, SeekOrigin.Begin) |> ignore
        using (new GZipStream(memoryStream, CompressionMode.Decompress, true)) <| fun gzipStream ->
            using(new MemoryStream()) <| outStream ->
                gzipStream.CopyTo(outStream)
                Encoding.UTF8.GetString(outStream.ToArray())