This tutorial is very simple and presents some elements related to BufferedStream and MemoryStream.
It is a simple example of using these functions that apply to .NET 7 and other versions.
You need to change the disk letter with yours because on this I have mapped a drive to the letter E.
Create a console project in C# Visual Studio called BufferedStream_and_MemoryStream and add the following source code:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 | using System; using System.Collections; using System.IO; using System.Text; namespace MyApp // Note: actual namespace depends on the project name. { internal class Program { static void Main(string[] args) { Console.WriteLine("Hello World!"); //BufferedStream class in C# using (FileStream fileStream = new FileStream("E:\\MyTextFile.txt", FileMode.Create, FileAccess.ReadWrite)) { BufferedStream bufferedStream = new BufferedStream(fileStream, 1024); byte[] bytes_BufferedStream = Encoding.ASCII.GetBytes("This is a sample text."); bufferedStream.Write(bytes_BufferedStream); bufferedStream.Flush(); bufferedStream.Close(); } //MemoryStream class in C# byte[] bytes_MemoryStream = System.Text.Encoding.ASCII.GetBytes("This is a new sample text in memory."); using (MemoryStream memoryStream = new MemoryStream(50)) { memoryStream.Write(bytes_MemoryStream, 0, bytes_MemoryStream.Length); // set the read for memoryStream memoryStream.Flush(); memoryStream.Position = 0; // create a readerstream StreamReader myStreamReader = new StreamReader(memoryStream); // read the string string read_MemoryStream = myStreamReader.ReadToEnd(); // show the result Console.WriteLine(" Memory stream string is : " + read_MemoryStream); } // } } } |
The result is this text in the console application:
1 2 | Hello World! Memory stream string is : This is a new sample text in memory. |