Stream.Close 方法


关闭当前流并释放与之关联的所有资源(如套接字和文件句柄)。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. 可以在usingStream (或Using Visual Basic 中的块)中声明对象,以确保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.

除非显式调用或Flush Close的实现,否则刷新流将不会刷新其基础编码器。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.


在派生类中,不要重写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.