2016-06-17 76 views
1

這裏是我的C#方法的zlib壓縮數據和一些額外的數據寫入流:DeflateStream關閉輸入流

using (var compressor = new DeflateStream(compressStream, CompressionMode.Compress)) { 
    compressor.Write(input, 0, input.Length); 
    compressor.Close(); 
    compessStream.Write(extraData, 0, extraData.Length); 
    } 

compressor.Close()被調用時,它會自動關閉輸入流。因此,我無法將額外的數據寫入流中。

如果我在寫入額外數據後關閉壓縮機,數據順序不再有效。我的額外數據在壓縮數據之前寫入,而不是按照我的意圖寫入。

爲什麼DeflateStream.Close()也關閉輸入流?有沒有辦法避免寫一個包裝實際流類並阻止後者關閉的流類?問候。

[__DynamicallyInvokable] 
protected override void Dispose(bool disposing) 
{ 
    try { 
     this.PurgeBuffers(disposing); 
    } 
    finally { 
     try { 
      if (disposing && !this._leaveOpen && this._stream != null) { 
       this._stream.Close(); 
      } 
     } 
     finally { 
      this._stream = null; 
      try { 
       if (this.deflater != null) { 
        this.deflater.Dispose(); 
       } 
      } 
      finally { 
       this.deflater = null; 
       base.Dispose(disposing); 
      } 
     } 
    } 
} 

默認情況下,DeflateStream擁有底層流,所以關閉流也會關閉底層流:

+3

'新DeflateStream(compressStream,CompressionMode.Compress,leaveOpen:真)' – PetSerAl

回答

0

的DeflateStream收盤時/處置,因爲它設計成這樣關閉底層流。

您可以通過使用specific constructor下,允許你離開底層流開DeflateStream控制這一行爲:

public DeflateStream(
    Stream stream, 
    CompressionMode mode, 
    bool leaveOpen 
) 
+0

參數「 leaveOpen「的伎倆。謝謝。 – Peter