Read Write MemoryStream
To perform Read write operations on MemoryStream instance, you need to use StreamReader and StreamWriter. Dealing with MemoryStream instance doesn't require disk input output operations. Here we will see both C#.net and Vb.net examples.
Memory stream is not expandable. If you pass byte array to constructor of Memory stream instance and tries to insert something, it will throw above exception To work with expandable memory stream, create MemoryStream instance without parameterized constructor.
C# Read Write MemoryStream example.
using System;
using System.IO;
using System.Text;
namespace Csharp.stringVsString.Example
{
class Program
{
static void Main(string[] args)
{
MemoryStream ms = new MemoryStream();
StreamReader reader = new StreamReader(ms);
StreamWriter writer = new StreamWriter(ms);
writer.Write("It will write new line on memory stream instance");
writer.Flush();
writer.WriteLine("writer.Flush() method writes buffers to memory Stream");
writer.WriteLine("Let's read the memory stream using stream reader");
writer.Flush();
ms.Seek(0,SeekOrigin.Begin);
Console.WriteLine(reader.ReadToEnd());
reader.Close();
writer.Close();
ms.Close();
Console.ReadLine();
}
}
}
VB.net Read Write Example of MemoryStream.
Imports System
Imports System.IO
Imports System.Text
Namespace Csharp.stringVsString.Example
Class Program
Private Shared Sub Main(args As String())
Dim ms As New MemoryStream()
Dim reader As New StreamReader(ms)
Dim writer As New StreamWriter(ms)
writer.Write("It will write new line on memory stream instance")
writer.Flush()
writer.WriteLine("writer.Flush() method writes buffers to memory Stream")
writer.WriteLine("Let's read the memory stream using stream reader")
writer.Flush()
ms.Seek(0, SeekOrigin.Begin)
Console.WriteLine(reader.ReadToEnd())
reader.Close()
writer.Close()
ms.Close()
Console.ReadLine()
End Sub
End Class
End Namespace
Output:
It will write new line on memory stream instancewriter.Flush() method writes buffers to memory Stream
Let's read the memory stream using stream reader
Note Don't forget to seek the pointer at the beginning of the memory stream. Otherwise, you would not be able to read the stream.
Currently rated 5.0 by 1 people
- Currently 5/5 Stars.
- 1
- 2
- 3
- 4
- 5