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 with buffers to assist load knowledge into reminiscence extra effectively. The System.IO namespace in .NET has many courses that work with streams, resembling FileStream, MemoryStream, FileInfo, and StreamReader/Author courses.
Principally, streams are labeled as both byte streams or character streams, the place byte streams take care of knowledge represented as bytes and character streams take care of characters. In .NET, the byte streams embody the Stream, FileStream, MemoryStream, and BufferedStream courses. The .NET character streams embody TextReader, TextWriter, StreamReader, and StreamWriter.
This text illustrates using the BufferedStream and MemoryStream courses in C#, with related code examples wherever relevant. To work with the code examples supplied on this article, you must have Visible Studio 2022 put in in your system. When you don’t have already got a replica, you may download Visual Studio 2022 here.
Create a console utility undertaking in Visible Studio
First off, let’s create a .NET Core console utility undertaking in Visible Studio. Assuming Visible Studio 2022 is put in in your system, observe the steps outlined beneath to create a brand new .NET Core console utility undertaking in Visible Studio.
- Launch the Visible Studio IDE.
- Click on on “Create new undertaking.”
- Within the “Create new undertaking” window, choose “Console App (.NET Core)” from the record of templates displayed.
- Click on Subsequent.
- Within the “Configure your new undertaking” window proven subsequent, specify the identify and placement for the brand new undertaking.
- Click on Subsequent.
- Within the “Further info” window proven subsequent, select “.NET 7.0 (Commonplace Time period Help)” because the Framework model you want to use.
- Click on Create.
We’ll use this .NET 7 console utility undertaking to work with the BufferedStream and MemoryStream courses within the subsequent sections of this text.
What’s a buffer?
A buffer represents a block of bytes in reminiscence the place you may briefly retailer transient knowledge. A buffer helps in minimizing the variety of calls your utility makes to learn and write knowledge from and to the file system. Buffers are helpful when you must retailer knowledge that’s being transferred from one pc system to a different or from one program part to a different.
Buffers are used along with streams to make it simpler for packages to learn and write knowledge effectively. Buffers retailer knowledge briefly in order that your utility needn’t hold re-reading the info from disk each time it’s requested.
Use the BufferedStream class in C#
The BufferedStream class represents a kind of stream that may buffer knowledge earlier than writing it to the stream. In different phrases, a buffered stream can learn or write knowledge right into a buffer, permitting you to learn or write bigger chunks of information without delay to enhance efficiency. You’ll be able to create buffered streams from reminiscence streams and file streams.
Whenever you create an occasion of the BufferedStream class, you may specify the buffer dimension as nicely. The default buffer dimension is 4096 bytes. Studying knowledge from a buffered stream includes studying from the buffer whenever you name the Learn methodology. Even should you name Learn a number of instances, the info might be fetched from the stream solely as soon as.
Whenever you write to a buffered stream, the info is written right into a buffer after which flushed to the stream whenever you name the Flush methodology. This improves efficiency by avoiding accessing the stream for each Write name. After 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 information in its inner buffer, BufferedStream can course of a number of operations on the identical chunk of reminiscence with out having to allocate reminiscence repeatedly. This protects each time and reminiscence consumption when creating new objects repeatedly.
Observe that you should use a BufferedStream occasion for both studying knowledge or writing knowledge, however you can not use the identical occasion for each operations. BufferedStream is designed to stop enter and output from slowing down when there is no such thing as a want for a buffer. A buffered stream could not even allocate an inner buffer if the learn and write dimension is at all times higher than the inner buffer dimension.
The next code snippet exhibits how one can write knowledge 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("This can be a pattern textual content.");
bufferedStream.Write(bytes);
bufferedStream.Flush();
bufferedStream.Shut();
}
When do you have to use BufferedStream? Use BufferedStream whenever you need to add help for buffering to an present stream. Thus if the unique stream had 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 means that you can write to or learn from a reminiscence buffer. The MemoryStream class helps the identical strategies and properties as these of the Stream class. MemoryStream offers a easy strategy to learn or write knowledge instantly from reminiscence, with out having to allocate and deallocate reminiscence each time you need to learn or write one thing. This makes it sooner than utilizing different strategies that require you to reallocate reminiscence on every use.
A reminiscence stream is a stream that may be very quick and environment friendly because the knowledge 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 gadgets that help studying and writing knowledge. The MemoryStream class can 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 knowledge to a reminiscence stream in C#.
byte[] bytes = System.Textual content.Encoding.ASCII.GetBytes("This can be 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 identify suggests, MemoryStream is a memory-only stream. As such, it ought to be used solely when the quantity of information 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 eventualities the place your utility requires sooner entry to knowledge. You need to use the async variations of the Learn and Write strategies of BufferedStream and MemoryStream courses for even higher efficiency and scalability.
Copyright © 2022 IDG Communications, Inc.