Byte-order marks are to inform readers of a file that the file is of a particular encoding. As such, you should only need the byte-order marks (BOM) in the actual file. If you want to include BOM in a text file you're writing, simply use StreamWriter
to write to the file. For example:
using(var writer = new StreamWriter(stream, System.Text.Encoding.UTF8))
{
writer.Write(sb.ToString);
}
If you don't want BOM with UTF-8:
using(var writer = new StreamWriter(stream))
{
writer.Write(sb.ToString());
}
Or if you want different BOM:
using(var writer = new StreamWriter(stream, System.Text.Encoding.UTF16))
{
writer.Write(sb.ToString);
}
Update:
If you wanted to be coupled from the implementation detail of a BOM or a BOM of a particular encoding (i.e. could change at runtime or after deployment) but still wanted to pass a BOM-marked string, you could do something like this (assumes .NET 4.5):
var stream = new MemoryStream();
var encoding = Encoding.UTF8; // TODO: configurize this, if necessary
using(var writer = new StreamWriter(stream, encoding, 1024, true))
{
writer.Write(sb.ToString());
}
CantModifyButMustUseThis(encoding.GetString(stream.ToArray());