Difference between Buffer & Stream in C#

As I said in my comment, the nutshell difference between a buffer and a stream is that a stream is a sequence that transfers information from or to a specified source, whereas a buffer is a sequence of bytes that is stored in memory. For example:

FileStream stream = new FileStream("filepath.txt", FileMode.OpenOrCreate);

Opens a stream to a file. That stream can be read from, written to, or both. As it doesn't require any additional memory, it's lightweight and fast, but arbitrarily referencing a particular set of data in the source can be cumbersome. Streams also benefit from being a connection rather than a discrete set of data, so you don't need to know the size of the data beforehand.

Conversely:

byte[] fileContents = File.ReadAllBytes("filepath.txt");

Reads all the bytes of a file into memory. This is handy for when you need to manipulate the entire file at once, or keep a "local copy" for your program to hold onto so the file can be free for other uses. Depending on the size of the source and the amount of available memory, though, a buffer containing the entire file might not be an option.

This is just a barebones explanation, though. There are more thorough ones out there, For example, as Marc Gravell puts it:

Many data-structures (lists, collections, etc) act as containers - they hold a set of objects. But not a stream; if a list is a bucket, then a stream is a hose. You can pull data from a stream, or push data into a stream - but normally only once and only in one direction (there are exceptions of course). For example, TCP data over a network is a stream; you can send (or receive) chunks of data, but only in connection with the other computer, and usually only once - you can't rewind the Internet.

Streams can also manipulate data passing through them; compression streams, encryption streams, etc. But again - the underlying metaphor here is a hose of data. A file is also generally accessed (at some level) as a stream; you can access blocks of sequential data. Of course, most file systems also provide random access, so streams do offer things like Seek, Position, Length etc - but not all implementations support such. It has no meaning to seek some streams, or get the length of an open socket.

Tags:

C#

Buffer

Stream