0

My question has already kind of been asked at Releasing underlying Stream returned by Application.GetResourceStream on WP7, but I have a couple variations on the question:

  1. This is for a desktop WPF application, not WP7 if it makes any difference.
  2. I have to decide whether to use a using block on a stream reader built on top of the stream.

Here's some code:

System.Windows.Resources.StreamResourceInfo ri = 
   App.GetResourceStream(new Uri("Resources/Idioms.txt", UriKind.Relative));
using (System.IO.StreamReader sr = new System.IO.StreamReader(ri.Stream))
{
   idioms = sr.ReadToEnd().Split(lineSeps, StringSplitOptions.RemoveEmptyEntries);
}

Now StreamReader's close method (which I assume is the method that implements IDisposable.Dispose) indicates that it also closes the underlying stream (which I assume is also implementing IDisposable.Dispose).

So is this closing or disposing of the IO.Stream object provided by GetResourceStream's Stream property:

  1. Expected
  2. Acceptable, or
  3. Incorrect

(Should I use or avoid using on the reader built on top of the stream?)

Community
  • 1
  • 1
BlueMonkMN
  • 25,079
  • 9
  • 80
  • 146

1 Answers1

1

StreamReader's ctor has an overload that lets you tell it to keep the stream from being closed.

Also, you have it slightly backwards (unless I misunderstood). It's the Dispose method that calls Close, not the other way around.

Sam Axe
  • 33,313
  • 9
  • 55
  • 89
  • There is no accessible Dispose method on StreamReader so I assumed that the Close method is the one implementing Dispose on IDisposable. I suppose the other possibility is that it's private and only accessible when the object is cast to IDisposable. If the later is the case then I guess it would make sense for Dispose to call Close. But I see no reason Close and Dispose couldn't be doing the same thing. Can you continue to use a reader after it is closed, so long as it's not disposed? – BlueMonkMN Jan 02 '13 at 21:26
  • Also, my question remains, should I be taking advantage of the option to leave the stream open if the stream was on an object returned by GetResourceStream? I am using the code as shown in my question and not getting any errors. Can I then safely assume that I don't need to suppress the closing of the stream? – BlueMonkMN Jan 02 '13 at 21:30