To expand on what @OriginalGriff has said, here is an example of what he was talking about:
static void Main(string[] args)
{
using (MemoryStream memoryStream = new MemoryStream())
{
string textToWrite = "Hello, this is some text written to a MemoryStream!";
byte[] bytesToWrite = Encoding.UTF8.GetBytes(textToWrite);
memoryStream.Write(bytesToWrite, 0, bytesToWrite.Length);
memoryStream.Seek(0, SeekOrigin.Begin);
ReadStream(memoryStream);
}
}
private static void ReadStream(MemoryStream memoryStream)
{
using (StreamReader reader = new StreamReader(memoryStream, Encoding.UTF8))
{
string textRead = reader.ReadToEnd();
Console.WriteLine("Text read from MemoryStream: " + textRead);
}
}
Notice that I am using a
using
statement that sets the scope of the usage within the braces. I do it with the
MemoryStream
and
StreamReader
classes. Both classes implement the
IDisposable
interface. So when the code goes out of scope, the
MemoryStream
and
StreamReader
classes will automatically call their
Close
methods from the implemented
IDisposable.Dispose
method and release any resources in use.
If you want to implement this manually, you would do the following:
static void Main(string[] args)
{
MemoryStream memoryStream = new MemoryStream();
string textToWrite = "Hello, this is some text written to a MemoryStream!";
byte[] bytesToWrite = Encoding.UTF8.GetBytes(textToWrite);
memoryStream.Write(bytesToWrite, 0, bytesToWrite.Length);
memoryStream.Seek(0, SeekOrigin.Begin);
ReadStream(memoryStream);
memoryStream.Close();
}
private static void ReadStream(MemoryStream memoryStream)
{
StreamReader reader = new StreamReader(memoryStream, Encoding.UTF8);
string textRead = reader.ReadToEnd();
Console.WriteLine("Text read from MemoryStream: " + textRead);
reader.Close();
}
Note: the above code is dangerous as it is possible for the instances not to be close. Hence why the
using
statement is used.