streams of light on the highway 1200

How to use BufferedStream and MemoryStream in C#

A stream is an abstraction about a sequence of bytes. You can think of it as a constant buffer that can be read or published to. Streams are generally utilized in conjunction with buffers to aid load details into memory more proficiently. The Procedure.IO namespace in .Web has lots of classes that perform with streams, this sort of as FileStream, MemoryStream, FileInfo, and StreamReader/Writer classes.

In essence, streams are labeled as either byte streams or character streams, in which byte streams deal with data represented as bytes and character streams deal with people. In .Internet, the byte streams incorporate the Stream, FileStream, MemoryStream, and BufferedStream classes. The .Net character streams contain TextReader, TextWriter, StreamReader, and StreamWriter.

This posting illustrates the use of the BufferedStream and MemoryStream lessons in C#, with suitable code illustrations anywhere applicable. To perform with the code examples supplied in this short article, you must have Visual Studio 2022 mounted in your process. If you really do not currently have a copy, you can obtain Visual Studio 2022 listed here.

Create a console software venture in Visual Studio

First off, let us develop a .Web Core console application challenge in Visual Studio. Assuming Visible Studio 2022 is mounted in your process, abide by the measures outlined down below to produce a new .Web Main console software project in Visible Studio.

  1. Start the Visible Studio IDE.
  2. Simply click on “Create new venture.”
  3. In the “Create new project” window, choose “Console App (.Internet Core)” from the checklist of templates displayed.
  4. Simply click Next.
  5. In the “Configure your new project” window demonstrated subsequent, specify the identify and locale for the new task.
  6. Click Future.
  7. In the “Additional information” window proven subsequent, choose “.Internet 7. (Standard Term Support)” as the Framework model you would like to use.
  8. Click on Generate.

We’ll use this .Web 7 console application undertaking to work with the BufferedStream and MemoryStream classes in the subsequent sections of this write-up.

What is a buffer?

A buffer signifies a block of bytes in memory the place you can temporarily retailer transient information. A buffer assists in reducing the selection of phone calls your application will make to browse and compose knowledge from and to the file method. Buffers are valuable when you need to keep facts that is getting transferred from just one computer process to a different or from 1 plan element to an additional.

Buffers are employed in conjunction with streams to make it simpler for systems to read through and create knowledge efficiently. Buffers store data briefly so that your software need to have not hold re-reading the facts from disk every time it is asked for.

Use the BufferedStream course in C#

The BufferedStream course signifies a type of stream that can buffer knowledge ahead of crafting it to the stream. In other phrases, a buffered stream can read through or create information into a buffer, making it possible for you to read through or publish greater chunks of knowledge at after to improve efficiency. You can generate buffered streams from memory streams and file streams.

When you produce an instance of the BufferedStream course, you can specify the buffer measurement as nicely. The default buffer measurement is 4096 bytes. Looking through knowledge from a buffered stream includes examining from the buffer when you simply call the Examine process. Even if you get in touch with Examine many instances, the data will be fetched from the stream only after.

When you generate to a buffered stream, the data is prepared into a buffer and then flushed to the stream when you phone the Flush method. This enhances efficiency by averting accessing the stream for each Produce phone. When we use a buffer, we do not execute writes or reads right until a particular quantity of operations have been asked for.

By storing some amount of knowledge in its inner buffer, BufferedStream can method many operations on the very same chunk of memory devoid of acquiring to allocate memory once again and once more. This saves both of those time and memory usage when building new objects repeatedly.

Note that you can use a BufferedStream instance for both studying information or producing information, but you are not able to use the exact same occasion for both of those operations. BufferedStream is created to avoid input and output from slowing down when there is no require for a buffer. A buffered stream may well not even allocate an interior buffer if the examine and create size is always greater than the internal buffer size.

The subsequent code snippet shows how you can write data to a file working with BufferedStream.

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

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

When ought to you use BufferedStream? Use BufferedStream when you want to add help for buffering to an present stream. As a result if the primary stream had been a community stream, the information sent to it would be cached in a little buffer before becoming penned to or retrieved from the community stream.

Employing the MemoryStream course in C#

The MemoryStream class signifies a lightweight stream that makes it possible for you to generate to or browse from a memory buffer. The MemoryStream course supports the exact same procedures and homes as these of the Stream course. MemoryStream delivers a simple way to read or publish info right from memory, with no getting to allocate and deallocate memory every single time you want to read through or publish something. This will make it a lot quicker than utilizing other strategies that call for you to reallocate memory on each and every use.

A memory stream is a stream that is incredibly quick and productive since the facts resides in the memory. Having said that, this also signifies that it can be quickly missing if the program crashes or the laptop or computer shuts down abruptly.

The MemoryStream class is element of the System.IO namespace. It can be used to go through from and publish to files, network connections, and other gadgets that support studying and creating facts. The MemoryStream class can also be applied for serializing an object into a stream of bytes for storage or transmission over a community link.

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

byte[] bytes = Program.Text.Encoding.ASCII.GetBytes("This is a sample text.")
using (MemoryStream memoryStream = new MemoryStream(50))

     memoryStream.Produce(bytes, , bytes.Size)

When really should you use MemoryStream? As its identify indicates, MemoryStream is a memory-only stream. As this kind of, it should really be utilised only when the total of info that requires to be cached is small plenty of to easily fit in memory.

Although BufferedStream is more rapidly and extra successful, MemoryStream is very well-suited for eventualities in which your application necessitates speedier access to facts. You can use the async versions of the Examine and Create methods of BufferedStream and MemoryStream classes for even better overall performance and scalability.

Copyright © 2022 IDG Communications, Inc.

Leave a Reply