The default encoding is File.AppendAllText

Existing code overloads File.AppendAllText(filename, text) to save the text to a file.

I need to be able to specify the encoding without breaking backward compatibility. If I used File.AppendAllText(filename, text, encoding) overloading, what encoding do I need to specify to ensure that the files were created exactly the same?

+7
source share
2 answers

Overloading the two arguments to AppendAllText () completes the call to the internal File.InternalAppendAllText() method using UTF-8 encoding without specification:

 [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)); 
+9
source

A quick look at the sources for File.AppenAllText shows 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 bytes of the UTF8 header.

+4
source

All Articles