Thursday, December 8, 2022
HomeITHow you can use BufferedStream and MemoryStream in C#

How you can use BufferedStream and MemoryStream in C#


A stream is an abstraction over a sequence of bytes. You’ll be able to consider it as a steady buffer that may be learn or written to. Streams are sometimes used along side buffers to assist load information into reminiscence extra effectively. The System.IO namespace in .NET has many lessons that work with streams, comparable to FileStream, MemoryStream, FileInfo, and StreamReader/Author lessons.

Mainly, streams are labeled as both byte streams or character streams, the place byte streams cope with information represented as bytes and character streams cope with characters. In .NET, the byte streams embrace the Stream, FileStream, MemoryStream, and BufferedStream lessons. The .NET character streams embrace TextReader, TextWriter, StreamReader, and StreamWriter.

This text illustrates the usage of the BufferedStream and MemoryStream lessons in C#, with related code examples wherever relevant. To work with the code examples offered on this article, you need to have Visible Studio 2022 put in in your system. When you don’t have already got a duplicate, you possibly can obtain Visible Studio 2022 right here.

Create a console utility mission in Visible Studio

First off, let’s create a .NET Core console utility mission in Visible Studio. Assuming Visible Studio 2022 is put in in your system, comply with the steps outlined beneath to create a brand new .NET Core console utility mission in Visible Studio.

  1. Launch the Visible Studio IDE.
  2. Click on on “Create new mission.”
  3. Within the “Create new mission” window, choose “Console App (.NET Core)” from the record of templates displayed.
  4. Click on Subsequent.
  5. Within the “Configure your new mission” window proven subsequent, specify the title and placement for the brand new mission.
  6. Click on Subsequent.
  7. Within the “Extra info” window proven subsequent, select “.NET 7.0 (Normal Time period Help)” because the Framework model you wish to use.
  8. Click on Create.

We’ll use this .NET 7 console utility mission to work with the BufferedStream and MemoryStream lessons within the subsequent sections of this text.

What’s a buffer?

A buffer represents a block of bytes in reminiscence the place you possibly can briefly retailer transient information. A buffer helps in minimizing the variety of calls your utility makes to learn and write information from and to the file system. Buffers are helpful when that you must retailer information that’s being transferred from one laptop system to a different or from one program part to a different.

Buffers are used along side streams to make it simpler for packages to learn and write information effectively. Buffers retailer information briefly in order that your utility needn’t preserve re-reading the info from disk each time it’s requested.

Use the BufferedStream class in C#

The BufferedStream class represents a sort of stream that may buffer information earlier than writing it to the stream. In different phrases, a buffered stream can learn or write information right into a buffer, permitting you to learn or write bigger chunks of knowledge without delay to enhance efficiency. You’ll be able to create buffered streams from reminiscence streams and file streams.

While you create an occasion of the BufferedStream class, you possibly can specify the buffer measurement as nicely. The default buffer measurement is 4096 bytes. Studying information from a buffered stream entails studying from the buffer while you name the Learn methodology. Even should you name Learn a number of occasions, the info will probably be fetched from the stream solely as soon as.

While you write to a buffered stream, the info is written right into a buffer after which flushed to the stream while you name the Flush methodology. This improves efficiency by avoiding accessing the stream for each Write name. Once we use a buffer, we don’t execute writes or reads till a sure variety of operations have been requested.

By storing some quantity of knowledge in its inner buffer, BufferedStream can course of a number of operations on the identical chunk of reminiscence with out having to allocate reminiscence many times. This protects each time and reminiscence consumption when creating new objects repeatedly.

Notice that you should utilize a BufferedStream occasion for both studying information or writing information, however you can’t use the identical occasion for each operations. BufferedStream is designed to stop enter and output from slowing down when there isn’t a want for a buffer. A buffered stream might not even allocate an inner buffer if the learn and write measurement is at all times better than the inner buffer measurement.

The next code snippet exhibits how one can write information to a file utilizing BufferedStream.

 
utilizing (FileStream fileStream = new FileStream("D:MyTextFile.txt", FileMode.Create, FileAccess.ReadWrite))
{
      BufferedStream bufferedStream = new BufferedStream(fileStream, 1024);
      byte[] bytes = Encoding.ASCII.GetBytes("It is a pattern textual content.");
      bufferedStream.Write(bytes);
      bufferedStream.Flush();
      bufferedStream.Shut();
}

When do you have to use BufferedStream? Use BufferedStream while you wish to add help for buffering to an present stream. Thus if the unique stream have been a community stream, the info despatched to it will be cached in a small buffer earlier than being written to or retrieved from the community stream.

Utilizing the MemoryStream class in C#

The MemoryStream class represents a light-weight stream that lets you write to or learn from a reminiscence buffer. The MemoryStream class helps the identical strategies and properties as these of the Stream class. MemoryStream supplies a easy solution to learn or write information straight from reminiscence, with out having to allocate and deallocate reminiscence each time you wish to learn or write one thing. This makes it quicker than utilizing different strategies that require you to reallocate reminiscence on every use.

A reminiscence stream is a stream that could be very quick and environment friendly because the information resides within the reminiscence. Nevertheless, this additionally implies that it may be simply misplaced if this system crashes or the pc shuts down abruptly.

The MemoryStream class is a part of the System.IO namespace. It may be used to learn from and write to information, community connections, and different units that help studying and writing information. The MemoryStream class may also be used for serializing an object right into a stream of bytes for storage or transmission over a community connection.

The next code snippet exhibits how one can write information to a reminiscence stream in C#.

 
byte[] bytes = System.Textual content.Encoding.ASCII.GetBytes("It is a pattern textual content.");
utilizing (MemoryStream memoryStream = new MemoryStream(50))
{
     memoryStream.Write(bytes, 0, bytes.Size);
}

When do you have to use MemoryStream? As its title suggests, MemoryStream is a memory-only stream. As such, it needs to be used solely when the quantity of knowledge that must be cached is sufficiently small to comfortably slot in reminiscence.

Whereas BufferedStream is quicker and extra environment friendly, MemoryStream is well-suited for situations the place your utility requires quicker entry to information. You should use the async variations of the Learn and Write strategies of BufferedStream and MemoryStream lessons for even higher efficiency and scalability.

Copyright © 2022 IDG Communications, Inc.

RELATED ARTICLES

LEAVE A REPLY

Please enter your comment!
Please enter your name here

- Advertisment -
Google search engine

Most Popular

Recent Comments