How to use BufferedStream and MemoryStream in C#

A stream is an abstraction over a sequence of bytes. You can consider of it as a constant buffer that can be study or created to. Streams are often utilized in conjunction with buffers to aid load information into memory additional competently. The Method.IO namespace in .Net has numerous lessons that get the job done with streams, these types of as FileStream, MemoryStream, FileInfo, and StreamReader/Author lessons.

Essentially, streams are labeled as either byte streams or character streams, wherever byte streams deal with information represented as bytes and character streams offer with figures. In .Internet, the byte streams include things like the Stream, FileStream, MemoryStream, and BufferedStream lessons. The .Net character streams consist of TextReader, TextWriter, StreamReader, and StreamWriter.

This posting illustrates the use of the BufferedStream and MemoryStream courses in C#, with applicable code examples where ever applicable. To operate with the code illustrations delivered in this short article, you should really have Visual Studio 2022 put in in your procedure. If you do not by now have a duplicate, you can download Visual Studio 2022 listed here.

Make a console software task in Visual Studio

To start with off, let’s produce a .Web Main console software venture in Visual Studio. Assuming Visual Studio 2022 is put in in your method, stick to the steps outlined under to make a new .Net Core console application challenge in Visible Studio.

  1. Start the Visual Studio IDE.
  2. Click on on “Create new job.”
  3. In the “Create new project” window, decide on “Console Application (.Net Main)” from the listing of templates exhibited.
  4. Click Next.
  5. In the “Configure your new project” window revealed following, specify the identify and area for the new venture.
  6. Simply click Up coming.
  7. In the “Additional information” window revealed next, pick “.Web 7. (Conventional Expression Support)” as the Framework variation you would like to use.
  8. Click Make.

We’ll use this .Web 7 console software job to work with the BufferedStream and MemoryStream lessons in the subsequent sections of this posting.

What is a buffer?

A buffer signifies a block of bytes in memory wherever you can quickly shop transient details. A buffer helps in minimizing the number of phone calls your software makes to go through and create details from and to the file system. Buffers are practical when you have to have to retail store facts that is remaining transferred from just one laptop or computer method to a further or from one particular program component to a further.

Buffers are utilised in conjunction with streams to make it a lot easier for plans to study and publish knowledge effectively. Buffers retail store knowledge briefly so that your application have to have not hold re-examining the info from disk just about every time it is requested.

Use the BufferedStream class in C#

The BufferedStream course signifies a style of stream that can buffer information just before creating it to the stream. In other text, a buffered stream can browse or generate details into a buffer, enabling you to read through or compose greater chunks of details at at the time to improve performance. You can develop buffered streams from memory streams and file streams.

When you make an instance of the BufferedStream class, you can specify the buffer sizing as properly. The default buffer measurement is 4096 bytes. Studying information from a buffered stream will involve studying from the buffer when you phone the Study method. Even if you simply call Study a number of periods, the knowledge will be fetched from the stream only once.

When you publish to a buffered stream, the information is prepared into a buffer and then flushed to the stream when you contact the Flush system. This enhances effectiveness by avoiding accessing the stream for every single Generate simply call. When we use a buffer, we do not execute writes or reads until eventually a certain number of operations have been requested.

By storing some amount of money of facts in its inside buffer, BufferedStream can course of action multiple operations on the exact same chunk of memory without owning to allocate memory again and once more. This saves both of those time and memory usage when building new objects consistently.

Take note that you can use a BufferedStream instance for both examining facts or writing details, but you are not able to use the exact occasion for the two functions. BufferedStream is designed to avert input and output from slowing down when there is no will need for a buffer. A buffered stream could not even allocate an interior buffer if the study and create sizing is usually better than the interior buffer measurement.

The subsequent code snippet shows how you can create knowledge to a file employing BufferedStream.

employing (FileStream fileStream = new FileStream("D:\MyTextFile.txt", FileMode.Build, FileAccess.ReadWrite))

      BufferedStream bufferedStream = new BufferedStream(fileStream, 1024)
      byte[] bytes = Encoding.ASCII.GetBytes("This is a sample text.")

When should really you use BufferedStream? Use BufferedStream when you want to insert assist for buffering to an existing stream. Consequently if the unique stream ended up a network stream, the knowledge despatched to it would be cached in a modest buffer ahead of becoming penned to or retrieved from the community stream.

Employing the MemoryStream class in C#

The MemoryStream class represents a light-weight stream that lets you to publish to or read from a memory buffer. The MemoryStream course supports the identical strategies and attributes as people of the Stream course. MemoryStream supplies a easy way to go through or produce data immediately from memory, without having having to allocate and deallocate memory each individual time you want to study or publish some thing. This will make it speedier than utilizing other approaches that have to have you to reallocate memory on each individual use.

A memory stream is a stream that is pretty fast and effective given that the info resides in the memory. However, this also usually means that it can be very easily missing if the software crashes or the computer system shuts down abruptly.

The MemoryStream course is component of the System.IO namespace. It can be employed to browse from and publish to documents, community connections, and other equipment that help reading through and producing information. The MemoryStream course can also be employed for serializing an item into a stream of bytes for storage or transmission more than a network link.

The adhering to code snippet exhibits how you can compose knowledge to a memory stream in C#.

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

     memoryStream.Publish(bytes, , bytes.Size)

When should you use MemoryStream? As its identify indicates, MemoryStream is a memory-only stream. As this sort of, it ought to be used only when the sum of details that requires to be cached is little enough to comfortably match in memory.

Though BufferedStream is speedier and extra successful, MemoryStream is nicely-suited for situations exactly where your software needs more quickly obtain to facts. You can use the async variations of the Study and Generate approaches of BufferedStream and MemoryStream courses for even improved efficiency and scalability.

Copyright © 2022 IDG Communications, Inc.

You may also like