C# MemoryStream Example
C# memoryStream is derived class inherited from Stream class. When you use Memory Stream it loads entire file into memory of the system and there is no disk I/O operations. As you are dealing with direct memory the performance of application is very high. It is useful when you do have plenty of physical memory [RAM] available for application. Here we will see both C#.net and Vb.net example of how to use memory stream class. If you want to process the files faster, use MemoryStream instance. Example here is very easy to understand and scope is very simple.
C# Memory stream example.
The example uses static method of File ReadAllBytes. It opens binary file and returns byte array. Stream reader is used to read content of actual file. Let's see C# example.
using System;
using System.IO;
namespace Csharp.MemoryStream.Example
{
class Program
{
static void Main(string[] args)
{
byte []arrBytes = File.ReadAllBytes(@"C:\Memory_Stream_Example.txt");
MemoryStream ms = new MemoryStream(arrBytes);
StreamReader reader = new StreamReader(ms);
Console.WriteLine(reader.ReadToEnd());
reader.Close();
ms.Close();
Console.ReadLine();
}
}
}
VB.net Memory stream example.
Imports System
Imports System.IO
Namespace Csharp.MemoryStream.Example
Class Program
Private Shared Sub Main(args As String())
Dim arrBytes As Byte() = File.ReadAllBytes("C:\Memory_Stream_Example.txt")
Dim ms As New MemoryStream(arrBytes)
Dim reader As New StreamReader(ms)
Console.WriteLine(reader.ReadToEnd())
reader.Close()
ms.Close()
Console.ReadLine()
End Sub
End Class
End Namespace
OutPut: Here are content of text file.
This is Example of Memory Stream.
The file is loaded into physical memory.
There is no disk input output operations, hence performance is
high.
This is very basic example of using memory stream instance in Dot net language.
Currently rated 3.0 by 2 people
- Currently 3/5 Stars.
- 1
- 2
- 3
- 4
- 5