What is a socially acceptable way to leave a stream after using it?

If you are developing an API, or even inside your own code, and your method accepts Stream , is your method obligated to check the position and reset to the beginning, provided that CanSeek is true before use?

If so, why is there no method that does all this in the Stream class itself?

Over the years, I have been caught several times, suggesting that Stream enters my method at position 0.

And is reset Stream correct, where possible, after using it?

Alternatively, should Stream always copy, not transfer directly? Seems a bit overkill to me.

+7
c #
source share
3 answers

Is this your method to check the position and reset at the beginning, if CanSeek is true before using it?

No, in this case, I expect the calling code to prepare the thread correctly.

Most common templates that share stream methods require that the pointer remain exactly after the last read / write, so this never occurs.

But best after use: do nothing.

+10
source share

Is this your method to check the position and reset at the beginning, if CanSeek is true before using it?

No, for two reasons:

  • this is not always possible (for example, if CanSeek is false), so it would be strange if you did this for some threads and not for others.
  • BCL classes do not. For example, StreamReader closes the underlying stream when it is placed; it does not restore it to its previous state.
+3
source share

I didnโ€™t want to update the question, as people already cast their voices, but they may not like this part :)

This is very interesting (thank you) and clearly shows the difference in thinking when developing code style reusable code and application code.

So, if its responsibility for the application for preparing Stream for the API (and it seems that we all agree), then we can โ€œraiseโ€ the useful logic into the extension method inside the application.

  /// <summary> /// Tries to set the stream to position 0 if required. /// </summary> /// <returns> /// False if the stream is not at position 0 and does not support seek operations. /// </returns> public static bool TrySetPositionZero(this Stream stream) { if (stream.Position > 0) { if (stream.CanSeek) { stream.Position = 0; return true; } else { return false; } } else { return true; } } 

The difference between this and just stream.Position = 0 is that it has a better chance of success since it will succeed in streams for direct access only when it is already at position 0.

0
source share

All Articles