How to use BufferedStream and MemoryStream in C#

0

A stream is an abstraction around a sequence of bytes. You can believe of it as a continual buffer that can be go through or published to. Streams are often made use of in conjunction with buffers to assist load info into memory a lot more effectively. The Procedure.IO namespace in .Net has quite a few classes that do the job with streams, this sort of as FileStream, MemoryStream, FileInfo, and StreamReader/Writer lessons.

Generally, streams are labeled as possibly byte streams or character streams, exactly where byte streams deal with knowledge represented as bytes and character streams offer with characters. In .Net, the byte streams consist of the Stream, FileStream, MemoryStream, and BufferedStream lessons. The .Internet character streams incorporate TextReader, TextWriter, StreamReader, and StreamWriter.

This post illustrates the use of the BufferedStream and MemoryStream classes in C#, with relevant code illustrations anywhere relevant. To do the job with the code examples supplied in this short article, you need to have Visible Studio 2022 mounted in your process. If you really do not by now have a duplicate, you can download Visual Studio 2022 right here.

Generate a console application project in Visible Studio

First off, let’s create a .Internet Main console software challenge in Visual Studio. Assuming Visible Studio 2022 is put in in your technique, follow the techniques outlined beneath to create a new .Internet Core console software venture in Visible Studio.

  1. Start the Visual Studio IDE.
  2. Click on “Create new job.”
  3. In the “Create new project” window, find “Console Application (.Web Main)” from the checklist of templates exhibited.
  4. Simply click Following.
  5. In the “Configure your new project” window revealed next, specify the name and area for the new challenge.
  6. Click on Future.
  7. In the “Additional information” window shown upcoming, pick “.Web 7. (Regular Term Support)” as the Framework variation you would like to use.
  8. Simply click Make.

We’ll use this .Internet 7 console software venture to work with the BufferedStream and MemoryStream lessons in the subsequent sections of this post.

What is a buffer?

A buffer represents a block of bytes in memory the place you can temporarily shop transient info. A buffer assists in reducing the quantity of phone calls your software makes to read and write data from and to the file system. Buffers are valuable when you have to have to store knowledge that is currently being transferred from 1 personal computer process to a different or from one method ingredient to yet another.

Buffers are used in conjunction with streams to make it less complicated for systems to study and produce info proficiently. Buffers shop knowledge temporarily so that your software want not keep re-looking at the data from disk just about every time it is requested.

Use the BufferedStream class in C#

The BufferedStream class signifies a type of stream that can buffer knowledge ahead of producing it to the stream. In other words and phrases, a buffered stream can go through or create details into a buffer, allowing for you to go through or publish larger sized chunks of details at once to enhance performance. You can generate buffered streams from memory streams and file streams.

When you produce an instance of the BufferedStream class, you can specify the buffer dimensions as nicely. The default buffer dimensions is 4096 bytes. Studying knowledge from a buffered stream consists of reading from the buffer when you connect with the Read method. Even if you phone Study various periods, the information will be fetched from the stream only when.

When you produce to a buffered stream, the info is published into a buffer and then flushed to the stream when you contact the Flush approach. This improves overall performance by staying away from accessing the stream for each and every Compose contact. When we use a buffer, we do not execute writes or reads right until a specific amount of functions have been requested.

By storing some amount of knowledge in its internal buffer, BufferedStream can system a number of operations on the identical chunk of memory with out having to allocate memory once again and yet again. This will save both of those time and memory usage when producing new objects consistently.

Notice that you can use a BufferedStream occasion for both examining data or producing details, but you simply cannot use the exact instance for both equally operations. BufferedStream is created to avoid enter and output from slowing down when there is no need to have for a buffer. A buffered stream might not even allocate an inside buffer if the go through and compose dimension is generally greater than the interior buffer dimension.

The pursuing code snippet demonstrates how you can compose details to a file making use of BufferedStream.

 
working with (FileStream fileStream = new FileStream("D:\MyTextFile.txt", FileMode.Develop, FileAccess.ReadWrite))

      BufferedStream bufferedStream = new BufferedStream(fileStream, 1024)
      byte[] bytes = Encoding.ASCII.GetBytes("This is a sample textual content.")
      bufferedStream.Produce(bytes)
      bufferedStream.Flush()
      bufferedStream.Close()

When must you use BufferedStream? Use BufferedStream when you want to incorporate help for buffering to an current stream. So if the first stream ended up a community stream, the knowledge despatched to it would be cached in a compact buffer before being published to or retrieved from the community stream.

Working with the MemoryStream course in C#

The MemoryStream class signifies a lightweight stream that makes it possible for you to write to or study from a memory buffer. The MemoryStream class supports the exact same techniques and homes as these of the Stream course. MemoryStream gives a uncomplicated way to study or generate facts specifically from memory, without obtaining to allocate and deallocate memory each time you want to browse or generate some thing. This helps make it quicker than utilizing other techniques that have to have you to reallocate memory on every use.

A memory stream is a stream that is really fast and successful considering that the knowledge resides in the memory. Even so, this also usually means that it can be quickly missing if the method crashes or the pc shuts down abruptly.

The MemoryStream class is aspect of the Program.IO namespace. It can be employed to browse from and produce to documents, network connections, and other gadgets that assistance studying and composing facts. The MemoryStream class can also be employed for serializing an object into a stream of bytes for storage or transmission above a network relationship.

The pursuing code snippet reveals how you can write info to a memory stream in C#.

 
byte[] bytes = Process.Text.Encoding.ASCII.GetBytes("This is a sample textual content.")
employing (MemoryStream memoryStream = new MemoryStream(50))

     memoryStream.Write(bytes, , bytes.Size)

When need to you use MemoryStream? As its title indicates, MemoryStream is a memory-only stream. As these kinds of, it really should be employed only when the quantity of knowledge that requires to be cached is small ample to easily in good shape in memory.

Although BufferedStream is quicker and additional productive, MemoryStream is properly-suited for eventualities wherever your application demands speedier entry to facts. You can use the async versions of the Browse and Produce strategies of BufferedStream and MemoryStream classes for even much better overall performance and scalability.

Copyright © 2022 IDG Communications, Inc.

Leave a Reply