【发布时间】:2012-06-26 21:21:24
【问题描述】:
我正在使用GZipStream 来压缩一个字符串,并且我修改了两个不同的示例来看看什么是有效的。第一个代码 sn-p 是 the example in the documentation 的一个经过大量修改的版本,它只返回一个空字符串。
public static String CompressStringGzip(String uncompressed)
{
String compressedString;
// Convert the uncompressed source string to a stream stored in memory
// and create the MemoryStream that will hold the compressed string
using (MemoryStream inStream = new MemoryStream(Encoding.Unicode.GetBytes(uncompressed)),
outStream = new MemoryStream())
{
using (GZipStream compress = new GZipStream(outStream, CompressionMode.Compress))
{
inStream.CopyTo(compress);
StreamReader reader = new StreamReader(outStream);
compressedString = reader.ReadToEnd();
}
}
return compressedString;
当我调试它时,我只能说没有从reader 中读取,即compressedString 是空的。但是,我写的第二种方法,从CodeProject snippet 修改是成功的。
public static String CompressStringGzip3(String uncompressed)
{
//Transform string to byte array
String compressedString;
byte[] uncompressedByteArray = Encoding.Unicode.GetBytes(uncompressed);
using (MemoryStream outStream = new MemoryStream())
{
using (GZipStream compress = new GZipStream(outStream, CompressionMode.Compress))
{
compress.Write(uncompressedByteArray, 0, uncompressedByteArray.Length);
compress.Close();
}
byte[] compressedByteArray = outStream.ToArray();
StringBuilder compressedStringBuilder = new StringBuilder(compressedByteArray.Length);
foreach (byte b in compressedByteArray)
compressedStringBuilder.Append((char)b);
compressedString = compressedStringBuilder.ToString();
}
return compressedString;
}
为什么第一个代码 sn -p 不成功,而另一个是?尽管它们略有不同,但我不知道为什么第二个 sn-p 中的微小变化允许它工作。我使用的示例字符串是SELECT * FROM foods f WHERE f.name = 'chicken';
【问题讨论】:
-
与流的位置有关吗?在阅读之前,您是否尝试过在方法 1 中寻找流的开头?
-
我在行前添加了
inStream.Seek(0L, SeekOrigin.Begin);:inStream.CopyTo(compress);,但该方法仍然返回一个空字符串。
标签: c# string gzipstream