我使用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);',但該方法仍然返回一個空字符串。 –