hultqvist
hultqvist

Reputation: 18461

Choice of direction in c# streams

Some streams in c# appear to have a "direction" in that they are meant to be used on one way. For some of them, such as FileStream and NetworkStream that makes sense, but others does not.

For example with a GZipStream you can either compress or decompress data by writing it to the stream depending on constructor parameters. CryptoStream on the other hand force the encrypted data to the far side where decryption is forced to a read operation and encryption is a write operation.

Especially when working with cryptographic implementations It has been annoying to be forced pushing the data in a specific direction.

Is there any specific design motivation for implementing some streams in one direction only?

Update: To clarify, what I'm looking for is an understanding on why a some designs only use a single direction, not what the choice of direction is. Did anyone think of this before and found a explanation or maybe there is none.

Receiving a running stream of data that need to be processed as soon as possible. Therefore you want to write the bytes to the decoding stream as they are received.

With CryptoStream there is no natural relation to how many bytes you put in the memorystream and how many bytes you can read decrypted. Here you must take implementation specific details into consideration such as block size.

GZipStream can handle this by changing the direction of the compression.

Upvotes: 1

Views: 338

Answers (3)

user5285420
user5285420

Reputation: 37

The stream direction is arbitrary to the implementer and sometimes it doesn't match up with the direction we would like to use.

e.g. FTP file downloader only accepts a write stream, but you want to read the stream instead. Or in Reverse, the FTP uploader only accepts a read stream, but you want to write to the stream instead.

Stream is about moving data in chunks so it can be changed to move in either direction.

Here's an implementation:

https://github.com/djpai/StreamConduit

Upvotes: 0

VVS
VVS

Reputation: 19612

If you think of the CryptoStream as a container for encrypted content, it becomes obvious that sth. you want to Read() out of it should be decryptet and sth. you Write() into it should be encrypted.

Upvotes: 1

Henk Holterman
Henk Holterman

Reputation: 273439

decryption is forced to a read operation and encryption is a write operation

Is there any specific design motivation for implementing some streams in one direction only?

Well, suppose it was the other way round. It sounds sensible to decrypt-while-writing to a file, but the data still has to come from somewhere.

Meaning you would need a Stream.CopyTo() and the occasional MemoryStream. And those are the tools you can use now as well.

The choice may have been slightly arbitrary but you need to pick a direction, and encrypt-while-writing seems (to me) the most natural.

Upvotes: 3

Related Questions