gpt4 book ai didi

c# - c#中的压缩字符串

转载 作者:太空宇宙 更新时间:2023-11-03 21:47:29 24 4
gpt4 key购买 nike

我正在使用以下代码来压缩 2 个字符串,它在压缩时效果很好。但是,当我尝试解压缩第二个字符串时,如果第一个字符串很短(大约 4 个字符),我得到 Block length does not match with its complement 异常。这是我用于压缩的类:

    using System;
using System.IO;
using System.IO.Compression;
using System.Text;

namespace CompressString {
internal static class StringCompressor
{
/// <summary>
/// Compresses the string.
/// </summary>
/// <param name="text">The text.</param>
/// <returns></returns>
public static string CompressString(string value)
{
//Transform string into byte[]
byte[] byteArray = new byte[value.Length];
int indexBA = 0;
foreach (char item in value.ToCharArray())
{
byteArray[indexBA++] = (byte)item;
}

//Prepare for compress
System.IO.MemoryStream ms = new System.IO.MemoryStream();
System.IO.Compression.GZipStream sw = new System.IO.Compression.GZipStream(ms,
System.IO.Compression.CompressionMode.Compress);

//Compress
sw.Write(byteArray, 0, byteArray.Length);
//Close, DO NOT FLUSH cause bytes will go missing...
sw.Close();

//Transform byte[] zip data to string
byteArray = ms.ToArray();
System.Text.StringBuilder sB = new System.Text.StringBuilder(byteArray.Length);
foreach (byte item in byteArray)
{
sB.Append((char)item);
}
ms.Close();
sw.Dispose();
ms.Dispose();

return sB.ToString();
}

/// <summary>
/// Decompresses the string.
/// </summary>
/// <param name="compressedText">The compressed text.</param>
/// <returns></returns>
public static string DecompressString(string sData)
{
byte[] byteArray = new byte[sData.Length];

int indexBa = 0;
foreach (char item in sData)
byteArray[indexBa++] = (byte)item;

MemoryStream memoryStream = new MemoryStream(byteArray);
GZipStream gZipStream = new GZipStream(memoryStream, CompressionMode.Decompress);

byteArray = new byte[1024];

StringBuilder stringBuilder = new StringBuilder();

int readBytes;
while ((readBytes = gZipStream.Read(byteArray, 0, byteArray.Length)) != 0)
{
for (int i = 0; i < readBytes; i++) stringBuilder.Append((char)byteArray[i]);
} gZipStream.Close(); memoryStream.Close(); gZipStream.Dispose(); memoryStream.Dispose(); return stringBuilder.ToString();
}
}

我在行中的 DecompressString 方法中遇到异常:

while ((readBytes = gZipStream.Read(byteArray, 0, byteArray.Length)) != 0)

最佳答案

对于收到错误消息“ block 长度与其补码不匹配”的其他人,如果您尝试解压缩未压缩的文件,则可能会发生这种情况。

关于c# - c#中的压缩字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16213015/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com