streams of light on the highway 1200

How to use BufferedStream and MemoryStream in C#

A stream is an abstraction around a sequence of bytes. You can feel of it as a continual buffer that can be examine or written to. Streams are normally used in conjunction with buffers to aid load information into memory more effectively. The Method.IO namespace in .Web has lots of classes that perform with streams, these kinds of as FileStream, MemoryStream, FileInfo, and StreamReader/Author courses.

Mainly, streams are categorised as both byte streams or character streams, wherever byte streams deal with facts represented as bytes and character streams offer with characters. In .Web, the byte streams include things like the Stream, FileStream, MemoryStream, and BufferedStream courses. The .Internet character streams include things like TextReader, TextWriter, StreamReader, and StreamWriter.

This report illustrates the use of the BufferedStream and MemoryStream classes in C#, with relevant code illustrations anywhere applicable. To get the job done with the code examples provided in this posting, you should have Visible Studio 2022 put in in your program. If you really do not now have a duplicate, you can down load Visible Studio 2022 below.

Make a console software venture in Visual Studio

Initially off, let’s build a .Internet Core console application undertaking in Visible Studio. Assuming Visual Studio 2022 is set up in your technique, abide by the ways outlined underneath to make a new .Internet Main console software challenge in Visible Studio.

  1. Start the Visible Studio IDE.
  2. Simply click on “Create new undertaking.”
  3. In the “Create new project” window, choose “Console Application (.Web Core)” from the list of templates displayed.
  4. Click Up coming.
  5. In the “Configure your new project” window shown future, specify the title and place for the new challenge.
  6. Click Subsequent.
  7. In the “Additional information” window shown following, decide on “.Web 7. (Conventional Term Assist)” as the Framework model you would like to use.
  8. Click on Develop.

We’ll use this .Web 7 console software project to get the job done with the BufferedStream and MemoryStream lessons in the subsequent sections of this short article.

What is a buffer?

A buffer represents a block of bytes in memory exactly where you can quickly retailer transient facts. A buffer aids in reducing the number of phone calls your software can make to read and compose details from and to the file process. Buffers are practical when you will need to retail outlet information that is staying transferred from a single computer system process to another or from one method part to one more.

Buffers are made use of in conjunction with streams to make it less difficult for courses to study and produce information proficiently. Buffers retail outlet info temporarily so that your software will need not retain re-looking through the info from disk each individual time it is requested.

Use the BufferedStream class in C#

The BufferedStream course represents a kind of stream that can buffer info prior to creating it to the stream. In other terms, a buffered stream can read through or generate information into a buffer, enabling you to examine or publish much larger chunks of information at at the time to enhance effectiveness. You can generate buffered streams from memory streams and file streams.

When you create an instance of the BufferedStream class, you can specify the buffer dimensions as nicely. The default buffer measurement is 4096 bytes. Examining information from a buffered stream includes looking at from the buffer when you get in touch with the Read through method. Even if you contact Read through various instances, the knowledge will be fetched from the stream only after.

When you write to a buffered stream, the info is created into a buffer and then flushed to the stream when you contact the Flush approach. This increases performance by preventing accessing the stream for every Write contact. When we use a buffer, we do not execute writes or reads until eventually a particular selection of functions have been requested.

By storing some volume of facts in its inner buffer, BufferedStream can system numerous operations on the similar chunk of memory with out owning to allocate memory once again and yet again. This saves both time and memory intake when generating new objects repeatedly.

Take note that you can use a BufferedStream instance for both reading through information or creating information, but you can’t use the same instance for both of those operations. BufferedStream is built to avert input and output from slowing down when there is no require for a buffer. A buffered stream may possibly not even allocate an inside buffer if the read through and produce dimensions is constantly increased than the inside buffer sizing.

The following code snippet shows how you can publish facts to a file applying BufferedStream.

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

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

When should really you use BufferedStream? Use BufferedStream when you want to insert support for buffering to an existing stream. Therefore if the original stream have been a community stream, the knowledge despatched to it would be cached in a compact buffer right before getting created to or retrieved from the network stream.

Using the MemoryStream course in C#

The MemoryStream course signifies a light-weight stream that will allow you to compose to or examine from a memory buffer. The MemoryStream course supports the exact strategies and homes as individuals of the Stream class. MemoryStream delivers a simple way to examine or produce facts right from memory, devoid of possessing to allocate and deallocate memory just about every time you want to study or generate something. This makes it more quickly than using other techniques that require you to reallocate memory on each individual use.

A memory stream is a stream that is really fast and successful considering that the knowledge resides in the memory. On the other hand, this also means that it can be very easily dropped if the plan crashes or the computer system shuts down abruptly.

The MemoryStream class is aspect of the System.IO namespace. It can be made use of to read from and write to documents, community connections, and other products that help looking through and crafting knowledge. The MemoryStream course can also be utilised for serializing an object into a stream of bytes for storage or transmission around a network link.

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

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

     memoryStream.Publish(bytes, , bytes.Length)

When must you use MemoryStream? As its title suggests, MemoryStream is a memory-only stream. As this kind of, it need to be utilised only when the amount of information that desires to be cached is small ample to comfortably fit in memory.

When BufferedStream is a lot quicker and extra productive, MemoryStream is perfectly-suited for eventualities exactly where your application requires faster obtain to information. You can use the async versions of the Study and Publish solutions of BufferedStream and MemoryStream lessons for even superior performance and scalability.

Copyright © 2022 IDG Communications, Inc.