Existing code is calling the File.AppendAllText(filename, text) overload to save text to a file.
I need to be able to specify encoding without breaking backwards compatibility.  If I was to use the File.AppendAllText(filename, text, encoding) overload which encoding would I need to specify to ensure that files were created in exactly the same way?
The two arguments overload of AppendAllText() ends up calling the internal method File.InternalAppendAllText() using an UTF-8 encoding without BOM:
[SecuritySafeCritical]
public static void AppendAllText(string path, string contents)
{
    if (path == null) {
        throw new ArgumentNullException("path");
    }
    if (path.Length == 0) {
        throw new ArgumentException(
            Environment.GetResourceString("Argument_EmptyPath"));
    }
    File.InternalAppendAllText(path, contents, StreamWriter.UTF8NoBOM);
}
Therefore, you can write:
using System.IO;
using System.Text;
File.AppendAllText(filename, text, new UTF8Encoding(false, true));
                        A quick look at the sources for File.AppenAllText reveals the following implementation:
public static void AppendAllText(string path, string contents)
{
  // Removed some checks
  File.InternalAppendAllText(path, contents, StreamWriter.UTF8NoBOM);
}
internal static Encoding UTF8NoBOM
{
  get
  {
    if (StreamWriter._UTF8NoBOM == null)
    {
      StreamWriter._UTF8NoBOM = new UTF8Encoding(false, true);
    }
    return StreamWriter._UTF8NoBOM;
  }
}
So it looks like you want to pass an instance of UTF8Encoding without the UTF8 header bytes.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With