• Home
  • Insight
  • Blog
  • Business
  • Entertainment
  • Health
  • Politics
  • Shop
    • Gift Shop
    • Value Shop
    • Store
    • Bargain Shop
    • Discount
  • Sports
  • Tech
  • Travel
  • USA
  • Video
  • World
    • Asia
    • Africa
    • South America
    • North America
    • Europe
    • Oceania
Wednesday, November 18, 2026
No Result
View All Result
Subscribe Now
  • Home
  • Insight
  • Blog
  • Business
  • Entertainment
  • Health
  • Politics
  • Shop
    • Gift Shop
    • Value Shop
    • Store
    • Bargain Shop
    • Discount
  • Sports
  • Tech
  • Travel
  • USA
    Mary Peltola Emerges Victorious in Alaska Senate Race, Making History for Democrats

    Mary Peltola Emerges Victorious in Alaska Senate Race, Making History for Democrats

    Stranded in Conflict: Palestinians Navigate the Tenuous Balance of War and Peace Amid Ceasefire Efforts

    Stranded in Conflict: Palestinians Navigate the Tenuous Balance of War and Peace Amid Ceasefire Efforts

    Trump Administration Revokes Pay Increase for Head Start Educators

    Trump Administration Revokes Pay Increase for Head Start Educators

    Unexpected Triumph: Gay Candidates Achieve Unforeseen Victories in Challenging Races

    Unexpected Triumph: Gay Candidates Achieve Unforeseen Victories in Challenging Races

    Microsoft Outlook Experiences Prolonged Outage Affecting Users Nationwide

    Microsoft Outlook Experiences Prolonged Outage Affecting Users Nationwide

    Gunfire Erupts in D.C.: Authorities Search for Suspect Amid Rising Concerns Over Public Safety

    Gunfire Erupts in D.C.: Authorities Search for Suspect Amid Rising Concerns Over Public Safety

    LAUSD Takes Strong Action Against Hate Speech Following Racial Slur Incidents

    LAUSD Takes Strong Action Against Hate Speech Following Racial Slur Incidents

    Beloved Former Los Angeles Times Columnist Steve Harvey Passes Away at 80

    Beloved Former Los Angeles Times Columnist Steve Harvey Passes Away at 80

    Exploring Diversity: ‘Ten Lives’ Showcases the Varied Economic Journeys of Americans

    Exploring Diversity: ‘Ten Lives’ Showcases the Varied Economic Journeys of Americans

  • Video
  • World
    • Asia
    • Africa
    • South America
    • North America
    • Europe
    • Oceania
The Insight Post
  • Home
  • Insight
  • Blog
  • Business
  • Entertainment
  • Health
  • Politics
  • Shop
    • Gift Shop
    • Value Shop
    • Store
    • Bargain Shop
    • Discount
  • Sports
  • Tech
  • Travel
  • USA
    Mary Peltola Emerges Victorious in Alaska Senate Race, Making History for Democrats

    Mary Peltola Emerges Victorious in Alaska Senate Race, Making History for Democrats

    Stranded in Conflict: Palestinians Navigate the Tenuous Balance of War and Peace Amid Ceasefire Efforts

    Stranded in Conflict: Palestinians Navigate the Tenuous Balance of War and Peace Amid Ceasefire Efforts

    Trump Administration Revokes Pay Increase for Head Start Educators

    Trump Administration Revokes Pay Increase for Head Start Educators

    Unexpected Triumph: Gay Candidates Achieve Unforeseen Victories in Challenging Races

    Unexpected Triumph: Gay Candidates Achieve Unforeseen Victories in Challenging Races

    Microsoft Outlook Experiences Prolonged Outage Affecting Users Nationwide

    Microsoft Outlook Experiences Prolonged Outage Affecting Users Nationwide

    Gunfire Erupts in D.C.: Authorities Search for Suspect Amid Rising Concerns Over Public Safety

    Gunfire Erupts in D.C.: Authorities Search for Suspect Amid Rising Concerns Over Public Safety

    LAUSD Takes Strong Action Against Hate Speech Following Racial Slur Incidents

    LAUSD Takes Strong Action Against Hate Speech Following Racial Slur Incidents

    Beloved Former Los Angeles Times Columnist Steve Harvey Passes Away at 80

    Beloved Former Los Angeles Times Columnist Steve Harvey Passes Away at 80

    Exploring Diversity: ‘Ten Lives’ Showcases the Varied Economic Journeys of Americans

    Exploring Diversity: ‘Ten Lives’ Showcases the Varied Economic Journeys of Americans

  • Video
  • World
    • Asia
    • Africa
    • South America
    • North America
    • Europe
    • Oceania
No Result
View All Result
No Result
View All Result
Home Tech

How to use BufferedStream and MemoryStream in C#

by Theinsightpost
December 9, 2022
in Tech
0 0
0
How to use BufferedStream and MemoryStream in C#


A stream is an abstraction over a sequence of bytes. You can think of it as a continuous buffer that can be read or written to. Streams are often used in conjunction with buffers to help load data into memory more efficiently. The System.IO namespace in .NET has many classes that work with streams, such as FileStream, MemoryStream, FileInfo, and StreamReader/Writer classes.

Basically, streams are classified as either byte streams or character streams, where byte streams deal with data represented as bytes and character streams deal with characters. In .NET, the byte streams include the Stream, FileStream, MemoryStream, and BufferedStream classes. The .NET character streams include TextReader, TextWriter, StreamReader, and StreamWriter.

This article illustrates the use of the BufferedStream and MemoryStream classes in C#, with relevant code examples wherever applicable. To work with the code examples provided in this article, you should have Visual Studio 2022 installed in your system. If you don’t already have a copy, you can download Visual Studio 2022 here.

Create a console application project in Visual Studio

First off, let’s create a .NET Core console application project in Visual Studio. Assuming Visual Studio 2022 is installed in your system, follow the steps outlined below to create a new .NET Core console application project in Visual Studio.

  1. Launch the Visual Studio IDE.
  2. Click on “Create new project.”
  3. In the “Create new project” window, select “Console App (.NET Core)” from the list of templates displayed.
  4. Click Next.
  5. In the “Configure your new project” window shown next, specify the name and location for the new project.
  6. Click Next.
  7. In the “Additional information” window shown next, choose “.NET 7.0 (Standard Term Support)” as the Framework version you would like to use.
  8. Click Create.

We’ll use this .NET 7 console application project to work with the BufferedStream and MemoryStream classes in the subsequent sections of this article.

What is a buffer?

A buffer represents a block of bytes in memory where you can temporarily store transient data. A buffer helps in minimizing the number of calls your application makes to read and write data from and to the file system. Buffers are useful when you need to store data that is being transferred from one computer system to another or from one program component to another.

Buffers are used in conjunction with streams to make it easier for programs to read and write data efficiently. Buffers store data temporarily so that your application need not keep re-reading the data from disk every time it is requested.

Use the BufferedStream class in C#

The BufferedStream class represents a type of stream that can buffer data before writing it to the stream. In other words, a buffered stream can read or write data into a buffer, allowing you to read or write larger chunks of data at once to improve performance. You can create buffered streams from memory streams and file streams.

When you create an instance of the BufferedStream class, you can specify the buffer size as well. The default buffer size is 4096 bytes. Reading data from a buffered stream involves reading from the buffer when you call the Read method. Even if you call Read multiple times, the data will be fetched from the stream only once.

When you write to a buffered stream, the data is written into a buffer and then flushed to the stream when you call the Flush method. This improves performance by avoiding accessing the stream for every Write call. When we use a buffer, we do not execute writes or reads until a certain number of operations have been requested.

By storing some amount of data in its internal buffer, BufferedStream can process multiple operations on the same chunk of memory without having to allocate memory again and again. This saves both time and memory consumption when creating new objects repeatedly.

Note that you can use a BufferedStream instance for either reading data or writing data, but you cannot use the same instance for both operations. BufferedStream is designed to prevent input and output from slowing down when there is no need for a buffer. A buffered stream may not even allocate an internal buffer if the read and write size is always greater than the internal buffer size.

The following code snippet shows how you can write data to a file using BufferedStream.

 
using (FileStream fileStream = new FileStream("D:\\MyTextFile.txt", FileMode.Create, 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 you use BufferedStream? Use BufferedStream when you want to add support for buffering to an existing stream. Thus if the original stream were a network stream, the data sent to it would be cached in a small buffer before being written to or retrieved from the network stream.

Using the MemoryStream class in C#

The MemoryStream class represents a lightweight stream that allows you to write to or read from a memory buffer. The MemoryStream class supports the same methods and properties as those of the Stream class. MemoryStream provides a simple way to read or write data directly from memory, without having to allocate and deallocate memory every time you want to read or write something. This makes it faster than using other techniques that require you to reallocate memory on each use.

A memory stream is a stream that is very fast and efficient since the data resides in the memory. However, this also means that it can be easily lost if the program crashes or the computer shuts down abruptly.

The MemoryStream class is part of the System.IO namespace. It can be used to read from and write to files, network connections, and other devices that support reading and writing data. The MemoryStream class can also be used for serializing an object into a stream of bytes for storage or transmission over a network connection.

The following code snippet shows how you can write data to a memory stream in C#.

 
byte[] bytes = System.Text.Encoding.ASCII.GetBytes("This is a sample text.");
using (MemoryStream memoryStream = new MemoryStream(50))
{
     memoryStream.Write(bytes, 0, bytes.Length);
}

When should you use MemoryStream? As its name suggests, MemoryStream is a memory-only stream. As such, it should be used only when the amount of data that needs to be cached is small enough to comfortably fit in memory.

While BufferedStream is faster and more efficient, MemoryStream is well-suited for scenarios where your application requires faster access to data. You can use the async versions of the Read and Write methods of BufferedStream and MemoryStream classes for even better performance and scalability.

Copyright © 2022 IDG Communications, Inc.



Source link

ShareTweetSend
Previous Post

Maxine Waters Paid Daughter $8K with Campaign Cash

Next Post

With second straight three-point game, Jets’ Dubois proving he’s a man on a mission

Related News

Transform Your Laptop Setup with These 5 Affordable Accessories
Tech

Transform Your Laptop Setup with These 5 Affordable Accessories

November 15, 2026
Microsoft 365 Services Gradually Restore Functionality Following Global Outage
Tech

Microsoft 365 Services Gradually Restore Functionality Following Global Outage

November 14, 2026
Epic Seeks Accountability for Apple’s Alleged Disregard of Court Ruling Intent
Tech

Epic Seeks Accountability for Apple’s Alleged Disregard of Court Ruling Intent

November 13, 2026
European Cybersecurity Firms Make Strides Against U.S. Competitors, Yet American Companies Still Command 62% of the Market
Tech

European Cybersecurity Firms Make Strides Against U.S. Competitors, Yet American Companies Still Command 62% of the Market

November 13, 2026
Next Post
With second straight three-point game, Jets’ Dubois proving he’s a man on a mission

With second straight three-point game, Jets’ Dubois proving he’s a man on a mission

Discussion about this post

Subscribe To Our Newsletters

    Customer Support


    1251 Wilcrest Drive
    Houston, Texas
    77042 USA
    Call-832.795.1420
    e-mail – news@theinsightpost.com

    Subscribe To Our Newsletters

      Categories

      • Africa
      • Africa-East
      • African Sports
      • American Sports
      • Arts
      • Asia
      • Australia
      • Business
      • Business Asia
      • Business- Africa
      • Canada
      • Defense
      • Education
      • Egypt
      • Energy
      • Entertainment
      • Europe
      • European Soccer
      • Finance
      • Germany
      • Ghana
      • Health
      • Insight
      • International
      • Investing
      • Japan
      • Latest Headlines
      • Life & Living
      • Markets
      • Mobile
      • Movies
      • New Zealand
      • Nigeria
      • Politics
      • Scholarships
      • Science
      • South Africa
      • South America
      • Sports
      • Tech
      • Travel
      • Travel-Africa
      • UK
      • USA
      • Weather
      • World
      No Result
      View All Result

      Recent News

      Vintage Photo of Robert Pattinson and Daniel Craig Gains New Significance Amid Bond Casting Developments

      Vintage Photo of Robert Pattinson and Daniel Craig Gains New Significance Amid Bond Casting Developments

      November 18, 2026
      Top 7 Retirement Threats and Effective Strategies to Navigate Them

      Top 7 Retirement Threats and Effective Strategies to Navigate Them

      November 18, 2026
      Charting the Future: Unveiling the TEFCA 2026-2027 Workplan and Innovative Monthly Metrics

      Charting the Future: Unveiling the TEFCA 2026-2027 Workplan and Innovative Monthly Metrics

      November 18, 2026
      Inevitable Buyer’s Remorse Looms Over Midterm Elections

      Inevitable Buyer’s Remorse Looms Over Midterm Elections

      November 18, 2026
      • Home
      • Advertise With Us
      • About Us
      • Corporate
      • Consumer Rewards
      • Forum
      • Privacy Policy
      • Social Trends

      Theinsightpost ©2026 | All Rights Reserved. Theinsightpost is an Elnegy LLC company, registered in Texas, USA

      Welcome Back!

      Login to your account below

      Forgotten Password?

      Retrieve your password

      Please enter your username or email address to reset your password.

      Log In

      Add New Playlist

      We are using cookies to give you the best experience on our website.

      You can find out more about which cookies we are using or switch them off in .

      No Result
      View All Result
      • Home
      • Insight
      • Blog
      • Business
      • Entertainment
      • Health
      • Politics
      • Shop
        • Gift Shop
        • Value Shop
        • Store
        • Bargain Shop
        • Discount
      • Sports
      • Tech
      • Travel
      • USA
      • Video
      • World
        • Asia
        • Africa
        • South America
        • North America
        • Europe
        • Oceania

      Theinsightpost ©2026 | All Rights Reserved. Theinsightpost is an Elnegy LLC company, registered in Texas, USA

      The Insight Post
      Powered by  GDPR Cookie Compliance
      Privacy Overview

      This website uses cookies so that we can provide you with the best user experience possible. Cookie information is stored in your browser and performs functions such as recognising you when you return to our website and helping our team to understand which sections of the website you find most interesting and useful.

      Strictly Necessary Cookies

      Strictly Necessary Cookie should be enabled at all times so that we can save your preferences for cookie settings.

      Cookie Policy

      More information about our Cookie Policy