Anonymous instances and disposal

  • Thread starter Thread starter Navaneeth.K.N
  • Start date Start date
N

Navaneeth.K.N

using(BinaryReader reader = new BinaryReader(new FileStream(filePathName,
FileMode.Open)))
{
//do something here
}
I have seen this code in one of the discussion forum. In this will file
stream instance supplied get disposed when BinaryReader disposes ?

Thanks
 
using(BinaryReader reader = new BinaryReader(new FileStream(filePathName,
FileMode.Open)))
{
//do something here}

I have seen this code in one of the discussion forum. In this will file
stream instance supplied get disposed when BinaryReader disposes ?

Yes, BinaryReader will dispose of its underlying stream when Dispose
is called on the BinaryReader.

Jon
 
It should, yes.

I've experienced problem with this kind of instansiation - don't know
why I got strange behavior. But taking out the FileStream
instantiation solved the problem. Basically the code will look like:

using (FileStream fs = new new FileStream(filePathName,
FileMode.Open))
using (BinaryReader reader = new BinaryReader(fs)
{
//TODO:
}
 
Well, if you can post a concise-but-complete code example that reliably  
demonstrates whatever "problem" or "strange behavior" you think you're  
seeing, it might be possible to explain what's going on.

That doesn't change the previous answers though.

Pete
Pete -
Sorry, I don't have the code snippet with now. To brief the the
problem , I was writing data to the file with filemode create and
fileacess write, using StreamWriter and anonymous FileStream. And I
had a consequent access to the same file and it threw access denied
error saying the file is in use. But using a separate filestream
instance within using block didn't cause that problem.Please share
your thoughts on this.
 
Aneesh said:
Pete -
Sorry, I don't have the code snippet with now. To brief the the
problem , I was writing data to the file with filemode create and
fileacess write, using StreamWriter and anonymous FileStream. And I
had a consequent access to the same file and it threw access denied
error saying the file is in use. But using a separate filestream
instance within using block didn't cause that problem.Please share
your thoughts on this.

The Dispose method of BinaryReader closes the internal stream, you
should not have any problems with the file being in use because of this.

As Peter mentioned, a concise program showing the problemw would be
helpful in determining what exactly is the problem.
 
Back
Top