开发者

What is the simplest method to get a stream from a string

开发者 https://www.devze.com 2023-03-11 09:05 出处:网络
Is there an accepted idiom or a quick and simple way to get a stream representation of a string? Or is my best bet a new MemoryStream(Encoding.Unicode.GetBytes(myStr)) where myStr is som开发者_StackO

Is there an accepted idiom or a quick and simple way to get a stream representation of a string?

Or is my best bet a new MemoryStream(Encoding.Unicode.GetBytes(myStr)) where myStr is som开发者_StackOverflow社区e string variable?


Assuming you want UTF8, then yes the code shown in the question is entirely correct.

The only thing I would change is: consider whether your API should actually be talking about TextReader rather than Stream. If so, new StringReader(myStr) would do nicely.

But for arbitrary binary Stream usage, your code is correct as shown (especially if you add a using, although in reality that is moot since for MemoryStream it is a no-op Dispose(); but I'm fussy ;p)

0

精彩评论

暂无评论...
验证码 换一张
取 消