Skip to content

[Breaking Change] StreamWriter keeps working after being disposed if leaveOpen: true is used #89646

Closed as not planned

Description

@jozkee

In below snippet I was expecting an exception to be thrown but instead the StreamWriter keeps working:

var ms = new MemoryStream();
var sw = new StreamWriter(ms, leaveOpen: true);

sw.Write("Hello");
sw.Dispose();

sw.Write(" World");
sw.Flush();
Console.WriteLine(Encoding.UTF8.GetString(ms.ToArray())); // prints "Hello World".

If I change leaveOpen to false, it does throw as I expected.

Originally posted by @jozkee in #89477 (comment)

cc @Neme12 @dersia


[Breaking Change] StreamWriter keeps working after being disposed if leaveOpen: true is used

We are fixing StreamWriter so that it correctly throws ObjectDisposedException after Dispose() / DisposeAsync() when constructed with leaveOpen: true. The fix is currently in PR #125189.

Related:

Goal

The goal is to align StreamWriter disposal behavior with StreamReader and standard IDisposable semantics. When leaveOpen: true, Dispose() should mark the writer as disposed (so subsequent operations throw) while leaving the underlying stream open. Currently, the _disposed flag is never set when leaveOpen: true, which means write and flush calls silently succeed after disposal.

Existing Behavior

When a StreamWriter is constructed with leaveOpen: true and then disposed, subsequent Write, Flush, and async variants continue to work without throwing any exception:

var ms = new MemoryStream();
var sw = new StreamWriter(ms, leaveOpen: true);
sw.Write("Hello");
sw.Dispose();
sw.Write(" World"); // No exception — writes succeed
sw.Flush();
Console.WriteLine(Encoding.UTF8.GetString(ms.ToArray()));
// prints "Hello World"

Note: StreamReader with the same leaveOpen: true flag correctly throws ObjectDisposedException after disposal. This inconsistency has existed since the leaveOpen parameter was introduced.

Breaking Change

After this fix, all write and flush operations on a disposed StreamWriter throw ObjectDisposedException, regardless of the leaveOpen parameter:

var ms = new MemoryStream();
var sw = new StreamWriter(ms, leaveOpen: true);
sw.Write("Hello");
sw.Dispose();
sw.Write(" World"); // Now throws ObjectDisposedException

The change is technically breaking because code that relied on the ability to write after disposal with leaveOpen: true will now throw at runtime. However, use-after-dispose is always documented as erroneous behavior in .NET, so we expect the practical impact to be low.

Error: System.ObjectDisposedException: Cannot write to a closed TextWriter.

Workaround: Remove usage patterns that write to a StreamWriter after calling Dispose() or DisposeAsync(). If you need to continue writing to the underlying stream, create a new StreamWriter wrapping it.

Affected APIs: All overloads of StreamWriter.Write, StreamWriter.WriteLine, StreamWriter.WriteAsync, StreamWriter.WriteLineAsync, StreamWriter.Flush, and StreamWriter.FlushAsync.

Feedback

We would love your feedback on this change. If you have scenarios where you depend on the current (pre-fix) behavior, please comment on this issue.

Activity

  1. ghost added
    untriaged
    on Jul 28, 2023
  2. added this to the Future milestone on Jul 28, 2023
  3. ghost removed
    untriaged
    on Jul 28, 2023
  4. changed the title [-]StreamWriter doesn't throw after being disposed[/-] [+]StreamWriter keeps working after being disposed if `leaveOpen: true` is used[/+] on Jul 28, 2023
  5. dersia commented on Jul 28, 2023

    @dersia
  6. Neme12 commented on Jul 28, 2023

    @Neme12

    Note: This works as expected on StreamReader, i.e. it throws after being disposed, regardless of the value of leaveOpen.

  7. dersia commented on Jul 28, 2023

    @dersia
  8. Neme12 commented on Jul 28, 2023

    @Neme12

    @dersia I meant StreamReader. I fixed the comment.

  9. added
    breaking-change
    on Jul 28, 2023
  10. ghost added
    needs-breaking-change-doc-created
    on Jul 28, 2023
  11. removed
    breaking-change
    needs-breaking-change-doc-created
    on Jul 28, 2023
  12. jozkee commented on Jul 28, 2023

    @jozkee
    MemberAuthor

    If we fix this someone somewhere will likely get broken, so we either don't fix it or we do and document it as a breaking change.

  13. dersia commented on Jul 28, 2023

    @dersia
  14. Neme12 commented on Jul 28, 2023

    @Neme12

    I would also like to put a bit more thought into it also for the Reader (it isn't really throwing because there is no operation called on the reader that checks for dispose, for the writer this happens during flush)

    StreamReader does throw when disposed:
    image

  15. dersia commented on Jul 28, 2023

    @dersia
  16. dersia commented on Jul 29, 2023

    @dersia

    I would also like to put a bit more thought into it also for the Reader (it isn't really throwing because there is no operation called on the reader that checks for dispose, for the writer this happens during flush)

    StreamReader does throw when disposed: image

    So I looked into the code and found out, why the Reader tests aren't throwing, although your testing throws. And I am not sure, if what I found is a as bad sign as I think it is. So basically the test are not really testing StreamReader, they are testing an internal derived class called NullStreamReader

    internal sealed class NullStreamReader : StreamReader
    which overrides Dispose:

    protected override void Dispose(bool disposing)
    {
        // Do nothing - this is essentially unclosable.
    }

    So the Tests on Stream.NullTest.cs won't test any of the Dispose logic of StreamReader. So there are now 2 different things I am wondering about.

    1. Should we remove the Dispose override on this class?
    2. do we need to override DisposeAync() on this class, now that DisposeAsync was newly added to StreamReader?

    Not sure which is the right option here. I think to be fully correct, one of the two need to happen as part of #89477 and right now I am leaning more towards the latter.
    Although, this makes all test that involve Reading after dispose useless.

  17. dersia commented on Jul 29, 2023

    @dersia

    So you think we should make the breaking change as part of this ticket and net8? I would suggest do get this in and then create a new bug ticket and fix and break it for net9, this would give us time to see if there are many broken during net9 preview times. not sure if so close to rc, this is a good thing to do. I would also like to put a bit more thought into it also for the Reader (it isn't really throwing because there is no operation called on the reader that checks for dispose, for the writer this happens during flush). I can also take care of that other ticket, since if have all the code for it and the PR for that other ticket could target milestone 9.

    As I was looking at this from my phone, I didn't realize that this is a separate issue, so don't mind this

  18. jeffhandley commented on Feb 8, 2026

    @jeffhandley
    Member

    Summary

    When StreamWriter is constructed with leaveOpen: true, calling Dispose() does not mark the writer as disposed. Subsequent Write and Flush calls succeed instead of throwing ObjectDisposedException. This is inconsistent with StreamReader, which correctly throws after disposal regardless of leaveOpen. Filed by @jozkee (MS employee) and confirmed as a genuine inconsistency.

    Expected Fix

    In StreamWriter.Dispose(bool), when leaveOpen is true, the method currently skips closing the underlying stream but also skips setting any "disposed" flag. The fix should set the internal _disposed flag (or null out the internal _stream field like the leaveOpen: false path does) so that subsequent operations throw ObjectDisposedException. Note: this is technically a breaking change since someone could be relying on the current behavior, but the team acknowledged it as a bug worth fixing.

    Test Coverage

    • Add a test: create StreamWriter with leaveOpen: true, dispose it, then call Write — should throw ObjectDisposedException.
    • Add a test: same scenario with DisposeAsync — should also throw on subsequent writes.
    • Add a test confirming StreamReader with leaveOpen: true already throws after dispose (parity check).
    • Ensure existing StreamWriter tests still pass.

    Repro

    var ms = new MemoryStream();
    var sw = new StreamWriter(ms, leaveOpen: true);
    
    sw.Write("Hello");
    sw.Dispose();
    
    sw.Write(" World"); // Should throw ObjectDisposedException, but doesn't
    sw.Flush();
    Console.WriteLine(Encoding.UTF8.GetString(ms.ToArray()));
    // Actual:   prints "Hello World"
    // Expected: ObjectDisposedException on sw.Write(" World")
  19. added
    in-pr
    on Mar 4, 2026
  20. changed the title [-]StreamWriter keeps working after being disposed if `leaveOpen: true` is used[/-] [+][Breaking Change] StreamWriter keeps working after being disposed if `leaveOpen: true` is used[/+] on Mar 4, 2026
  21. removed
    in-pr
    on Mar 17, 2026
  22. ViveliDuCh commented on Mar 17, 2026

    @ViveliDuCh
    Member

    The consensus in #125189 is that the risk of breaking existing code outweighs the benefit given no active customer demand. Preserving the current behavior for backward compatibility.

  23. locked and limited conversation to collaborators on Apr 16, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

Type

No type

Projects

No projects

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions