Well it writes the BOM because you are instructing it to, in the line
Encoding utf8WithoutBom = new UTF8Encoding(true);
true
means that the BOM should be emitted, using
Encoding utf8WithoutBom = new UTF8Encoding(false);
writes no BOM.
My objective is create a file using UTF-8 as Encoding and 8859-1 as CharSet
Sadly, this is not possible, either you write UTF-8 or not. I.e. as long as the characters you are writing are present in ISO Latin-1 it will look like a ISO 8859-1 file, however as soon as you output a character that is not covered by ISO 8859-1 (e.g. ?,?, ü) these characters will be written as a multibyte character.
To write true ISO-8859-1 use:
Encoding isoLatin1Encoding = Encoding.GetEncoding("ISO-8859-1");
Edit: After balexandre's comment
I used the following code for testing ...
var filePath = @"c:empest.txt";
var sb = new StringBuilder();
sb.Append("dsfaskd jlsadfj laskjdflasjdf asdkfjalksjdf lkjdsfljas dddd jflasjdflkjasdlfkjasldfl as????jdflkaslj d f");
Encoding isoLatin1Encoding = Encoding.GetEncoding("ISO-8859-1");
TextWriter tw = new StreamWriter(filePath, false, isoLatin1Encoding);
tw.WriteLine(sb.ToString());
tw.Close();
And the file looks perfectly well. Obviously, you should use the same encoding when reading the file.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…