Close a filestream without Flush()

后端 未结 7 2025
猫巷女王i
猫巷女王i 2021-01-03 20:42

Can I close a file stream without calling Flush (in C#)? I understood that Close and Dispose calls the Flush method first.

7条回答
  •  轻奢々
    轻奢々 (楼主)
    2021-01-03 21:29

    You don't have to call Flush() on Close()/Dispose(), FileStream will do it for you as you can see from its source code:

    http://referencesource.microsoft.com/#mscorlib/system/io/filestream.cs,e23a38af5d11ffffd3

        [System.Security.SecuritySafeCritical]  // auto-generated
        protected override void Dispose(bool disposing)
        {
            // Nothing will be done differently based on whether we are 
            // disposing vs. finalizing.  This is taking advantage of the
            // weak ordering between normal finalizable objects & critical
            // finalizable objects, which I included in the SafeHandle 
            // design for FileStream, which would often "just work" when 
            // finalized.
            try {
                if (_handle != null && !_handle.IsClosed) {
                    // Flush data to disk iff we were writing.  After 
                    // thinking about this, we also don't need to flush
                    // our read position, regardless of whether the handle
                    // was exposed to the user.  They probably would NOT 
                    // want us to do this.
                    if (_writePos > 0) {
                        FlushWrite(!disposing); // <- Note this
                    }
                }
            }
            finally {
                if (_handle != null && !_handle.IsClosed)
                    _handle.Dispose();
    
                _canRead = false;
                _canWrite = false;
                _canSeek = false;
                // Don't set the buffer to null, to avoid a NullReferenceException
                // when users have a race condition in their code (ie, they call
                // Close when calling another method on Stream like Read).
                //_buffer = null;
                base.Dispose(disposing);
            }
        }
    

提交回复
热议问题