Skip to main content

You are not logged in. Your edit will be placed in a queue until it is peer reviewed.

We welcome edits that make the post easier to understand and more valuable for readers. Because community members review edits, please try to make the post substantially better than how you found it, for example, by fixing grammar or adding additional resources and hyperlinks.

Required fields*

8
  • 54
    Just in case someone uses this with an XML string deserialization, I had to switch UTF8 to Unicode for it to work without a flag. Great post!!! Commented Feb 14, 2014 at 15:28
  • 3
    I like this one (with Rhyous's tweak and the trivial extra sugar for use as an extension method) better than the accepted answer; more flexible, fewer LOC and fewer objects involved (no explicit need for a StreamWriter) Commented May 11, 2015 at 18:58
  • 3
    new MemoryStream(Encoding.UTF8.GetBytes("\ufeff" + (value ?? "")) if you need to have the BOM included at the beginning of the stream Commented Dec 17, 2015 at 10:42
  • 8
    This is very compact syntax but it's going to cause a lot of allocations of byte[] so beware in high performance code. Commented Mar 19, 2017 at 19:08
  • 4
    This solution still left the opportunity to make the stream readonly. new MemoryStream( value, false ). You cannot make a stream readonly if you have to write it with a stream writer. Commented Nov 19, 2018 at 9:20