我想操纵一种算法来压缩 c# 中的长字符串和短字符串,我尝试过的所有算法都能够压缩长字符串但不能压缩短字符串(大约 5 个字符)。代码是:
using System;
using System.Collections.Generic;
using System.IO.Compression;
using System.IO;
using System.Collections;
using System.Text;
namespace CompressString {
internal static class StringCompressor
{
/// <summary>
/// Compresses the string.
/// </summary>
/// <param name="text">The text.</param>
/// <returns>compressed string</returns>
public static string CompressString(string text)
{
byte[] buffer = Encoding.Default.GetBytes(text);
MemoryStream ms = new MemoryStream();
using (GZipStream zip = new GZipStream(ms, CompressionMode.Compress, true))
{
zip.Write(buffer, 0, buffer.Length);
}
ms.Position = 0;
byte[] compressed = new byte[ms.Length];
ms.Read(compressed, 0, compressed.Length);
byte[] gzBuffer = new byte[compressed.Length + 4];
System.Buffer.BlockCopy(compressed, 0, gzBuffer, 4, compressed.Length);
System.Buffer.BlockCopy(BitConverter.GetBytes(buffer.Length), 0, gzBuffer, 0, 4);
return Encoding.Default.GetString(gzBuffer);
}
/// <summary>
/// Decompresses the string.
/// </summary>
/// <param name="compressedText">The compressed text</param>
/// <returns>uncompressed string</returns>
public static string DecompressString(string compressedText)
{
byte[] gzBuffer = Encoding.Default.GetBytes(compressedText);
using (MemoryStream ms = new MemoryStream())
{
int msgLength = BitConverter.ToInt32(gzBuffer, 0);
ms.Write(gzBuffer, 4, gzBuffer.Length - 4);
byte[] buffer = new byte[msgLength];
ms.Position = 0;
using (GZipStream zip = new GZipStream(ms, CompressionMode.Decompress))
{
zip.Read(buffer, 0, buffer.Length);
}
return Encoding.Default.GetString(buffer);
}
}
}}
我在以下行中的解压缩方法中得到了 InvalidDataException(解码时发现无效数据): zip.Read(buffer, 0, buffer.Length); 你有什么建议?