2016-10-20 104 views
0

我試圖在我的UWP應用程序中壓縮一些文本。我創造了這個方法,使其更容易稍後:GZIPStream壓縮總是返回10字節

public static byte[] Compress(this string s) 
{ 
    var b = Encoding.UTF8.GetBytes(s); 
    using (MemoryStream ms = new MemoryStream()) 
    using (GZipStream zipStream = new GZipStream(ms, CompressionMode.Compress)) 
    { 
     zipStream.Write(b, 0, b.Length); 
     zipStream.Flush(); //Doesn't seem like Close() is available in UWP, so I changed it to Flush(). Is this the problem? 
     return ms.ToArray(); 
    } 
} 

但不幸的是這總是返回10個字節,無論輸入的文本是什麼。是否因爲我在GZipStream上不使用.Close()

回答

1

您正在返回字節數據太早。 Close()方法被Dispose()方法取代。所以GZIP流只會在離開using(GZipStream) {}區塊時纔會被寫入。

public static byte[] Compress(string s) 
{ 
    var b = Encoding.UTF8.GetBytes(s); 
    var ms = new MemoryStream(); 
    using (GZipStream zipStream = new GZipStream(ms, CompressionMode.Compress)) 
    { 
     zipStream.Write(b, 0, b.Length); 
     zipStream.Flush(); //Doesn't seem like Close() is available in UWP, so I changed it to Flush(). Is this the problem? 
    } 

    // we create the data array here once the GZIP stream has been disposed 
    var data = ms.ToArray(); 
    ms.Dispose(); 
    return data; 
} 
+0

是的,這就像一個魅力!我之前嘗試過使用'.Dispose()',而不是在using()塊之外使用它,而是在返回數據之前調用它,導致'ms'也被丟棄。謝謝! – Reynevan