Florian
Florian

Reputation: 4728

What is the simplest way to convert a string to a stream?

Today, I use a memory stream :

new MemoryStream(Encoding.UTF8.GetBytes(str))

Is there a simpler / better way ?

Thank you !

Upvotes: 3

Views: 212

Answers (3)

Tigran
Tigran

Reputation: 62246

Don't know if there is simplest way or not, but I would say there is no better way (from the point of view of this question) to do this, as converting in memory, somehow you will need to convert it back. You need to know encodinig of the data you operate on.

In short: this is my prefered choice.

Upvotes: 1

Crab Bucket
Crab Bucket

Reputation: 6277

Try System.IO.StringReader class.

Upvotes: 2

Marc Gravell
Marc Gravell

Reputation: 1062770

That'll do it; there not really anything more direct than that, since you need the bytes (for the Stream API), hence need to go via an Encoding.

Note, however, that many APIs that take text-based data via a Stream will also accept a TextReader, and thus new StringReader(str) will be more direct.

Upvotes: 4

Related Questions