Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 8057749
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 5, 20262026-06-05T09:08:06+00:00 2026-06-05T09:08:06+00:00

Why using (var sw = new StreamWriter(ms)) returns Cannot access a closed Stream exception

  • 0

Why using (var sw = new StreamWriter(ms)) returns Cannot access a closed Stream exception while the MemoryStream is on top of this code?

using (var ms = new MemoryStream())
{
    using (var sw = new StreamWriter(ms))
    {                 
        sw.WriteLine("data");
        sw.WriteLine("data 2");
        ms.Position = 0;
        using (var sr = new StreamReader(ms))
        {
            Console.WriteLine(sr.ReadToEnd());                        
        }
    } //error here
}
  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-06-05T09:08:08+00:00Added an answer on June 5, 2026 at 9:08 am

    This is because the StreamReader closes the underlying stream automatically when being disposed of. The using statement does this automatically.

    However, the StreamWriter you’re using is still trying to work on the stream (also, the using statement for the writer is now trying to dispose of the StreamWriter, which is then trying to close the stream).

    The best way to fix this is: don’t use using and don’t dispose of the StreamReader and StreamWriter. See this question.

    using (var ms = new MemoryStream())
    {
        var sw = new StreamWriter(ms);
        var sr = new StreamReader(ms);
    
        sw.WriteLine("data");
        sw.WriteLine("data 2");
        ms.Position = 0;
    
        Console.WriteLine(sr.ReadToEnd());                        
    }
    

    If you feel bad about sw and sr being garbage-collected without being disposed of in your code (as recommended), you could do something like that:

    StreamWriter sw = null;
    StreamReader sr = null;
    
    try
    {
        using (var ms = new MemoryStream())
        {
            sw = new StreamWriter(ms);
            sr = new StreamReader(ms);
    
            sw.WriteLine("data");
            sw.WriteLine("data 2");
            ms.Position = 0;
    
            Console.WriteLine(sr.ReadToEnd());                        
        }
    }
    finally
    {
        if (sw != null) sw.Dispose();
        if (sr != null) sr.Dispose();
    }
    
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

Running the following code, I get an exception: using (var client = new Pop3Client())
I've got this toy code, works fine, using MySQL var r = new SimpleRepository(DB,
using (var file_stream = File.Create(users.xml)) { var serializer = new XmlSerializer(typeof(PasswordManager)); serializer.Serialize(file_stream, this); file_stream.Close();
I'm trying to do this: using(var context = new SampleEntities()) { User user =
Hay, i'm using this script function preloader(images){ var i = 0; imageObj = new
using ( var sw = new StreamWriter ( file ) ) { XmlSerializer xs
When serializing object with the code: var xmlSerializer = new XmlSerializer(typeof(MyType)); using (var xmlWriter
var fs = new FileStream(filePath, FileMode.OpenOrCreate, FileAccess.ReadWrite); using(var writer = new StreamWriter(fs)) writer.Write(....); If
With this code for a very basic logger: lock (string.Concat(LogWritter_, this.FileName)) { using (var
using (var client = new WebClient()) { html = client.DownloadString(some_string); //do something html =

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.