Stream.Close Method


關閉目前資料流和釋放與目前資料流相關聯的任何資源 (例如通訊端和檔案控制代碼)。Closes the current stream and releases any resources (such as sockets and file handles) associated with the current stream. 請確定正確地處置資料流,而非呼叫這個方法。Instead of calling this method, ensure that the stream is properly disposed.

 virtual void Close();
public virtual void Close ();
abstract member Close : unit -> unit
override this.Close : unit -> unit
Public Overridable Sub Close ()


這個方法會呼叫 Dispose,並指定 true 釋放所有資源。This method calls Dispose, specifying true to release all resources. 您不需要特別呼叫 Close 方法。You do not have to specifically call the Close method. 相反地,請確定已正確處置每個 Stream 物件。Instead, ensure that every Stream object is properly disposed. 您可以在 using 區塊(或 Visual Basic 中的 Using 區塊)中宣告 Stream 物件,以確保處置資料流程及其所有資源,或者您可以明確地呼叫 Dispose 方法。You can declare Stream objects within a using block (or Using block in Visual Basic) to ensure that the stream and all of its resources are disposed, or you can explicitly call the Dispose method.

除非您明確地呼叫 FlushClose的執行,否則清除資料流程不會排清其基礎編碼器。Flushing the stream will not flush its underlying encoder unless you explicitly call an implementation of Flush or Close. AutoFlush 設定為 true 表示資料將從緩衝區排清到資料流程,但是編碼器狀態將不會排清。Setting AutoFlush to true means that data will be flushed from the buffer to the stream, but the encoder state will not be flushed. 這可讓編碼器保留其狀態(部分字元),以便正確地編碼下一個字元區塊。This allows the encoder to keep its state (partial characters) so that it can encode the next block of characters correctly. 此案例會影響 UTF8 和 UTF7,在此情況下,只有在編碼器收到連續的字元之後,才可以將某些字元編碼。This scenario affects UTF8 and UTF7 where certain characters can be encoded only after the encoder receives the adjacent character or characters.

在資料流程關閉後嘗試運算元據流,可能會擲回 ObjectDisposedExceptionAttempts to manipulate the stream after the stream has been closed might throw an ObjectDisposedException.

Notes to Inheritors

在衍生類別中,請勿覆寫 Close() 方法,而是將所有 Stream 清除邏輯放在 Dispose(Boolean) 方法中。In derived classes, do not override the Close() method, instead, put all of the Stream cleanup logic in the Dispose(Boolean) method. 如需詳細資訊,請參閱執行 Dispose 方法For more information, see Implementing a Dispose Method.

Applies to

See also