I have a series of Read() overloads in a class.
Each opens the file only long enough to read, so I have:
public void Read(blah)
{
using (FileStream stream = new FileStream(Path, FileMode.Open, FileAccess.Read))
using (BinaryReader reader = new BinaryReader(stream))
{
//read some stuff
}
}
public void Read(blah blah)
{
using (FileStream stream = new FileStream(Path, FileMode.Open, FileAccess.Read))
using (BinaryReader reader = new BinaryReader(stream))
{
//read some different stuff
}
}
Is there any way of wrapping the stream and reader creation in a function, and yet still retain the using() to dispose everything automatically?
eg
public void Read(blah)
{
using (var reader = GetReader())
{
//read some stuff
}
}
public void Read(blah blah)
{
using (var reader = GetReader())
{
//read some different stuff
}
}
private BinaryReader GetReader()
{
//How do I dispose this stream?
FileStream stream = new FileStream(Path, FileMode.Open, FileAccess.Read))
return new BinaryReader(stream);
}
In this specific case, you don’t have to dispose your stream. Upon disposal, the BinaryReader will automatically dispose the underlying stream.
But maybe the BinaryReader is just an example?