Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

File.AppendAllText Default Encoding

Tags:

c#

encoding

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?

like image 559
Liath Avatar asked Jun 17 '13 09:06

Liath


2 Answers

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));
like image 130
Frédéric Hamidi Avatar answered Oct 19 '22 05:10

Frédéric Hamidi


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.

like image 27
Rune Grimstad Avatar answered Oct 19 '22 06:10

Rune Grimstad