My answer is based on HelloSam, which contains all the necessary information. Only I believe what the OP is asking for - how to make sure the specification is selected in the file.
So instead of passing false to UTF8Encoding ctor, you need to pass true.
using (var sw = new StreamWriter("text.txt", new UTF8Encoding(true)))
Try the code below, open the resulting files in a hex editor and see which one contains the specification and which does not.
class Program { static void Main(string[] args) { const string nobomtxt = "nobom.txt"; File.Delete(nobomtxt); using (Stream stream = File.OpenWrite(nobomtxt)) using (var writer = new StreamWriter(stream, new UTF8Encoding(false))) { writer.WriteLine("Hello"); } const string bomtxt = "bom.txt"; File.Delete(bomtxt); using (Stream stream = File.OpenWrite(bomtxt)) using (var writer = new StreamWriter(stream, new UTF8Encoding(true))) { writer.WriteLine("Hello"); } }
Nik Mar 19 '14 at 19:31 2014-03-19 19:31
source share