我使用GZipStream
来压缩一个字符串,我修改了两个不同的例子来看看有什么作用。第一个代码片段是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;
}
为什么第一个代码段不成功,而另一个是?尽管它们略有不同,但我不知道为什么第二个片段中的细微变化可以让它起作用。我使用的样本串SELECT * FROM foods f WHERE f.name = 'chicken';
任何与流的位置有关?在阅读之前,您是否尝试过在方法1中试图寻找流的开始? – Charleh
我添加了'inStream.Seek(0L,SeekOrigin.Begin);'在行之前:'inStream.CopyTo(compress);',但该方法仍然返回一个空字符串。 –