2013-06-17 10 views
7

Istniejący kod wywołuje przeciążenie File.AppendAllText(filename, text), aby zapisać tekst do pliku.File.AppendAllText Domyślne kodowanie

Potrzebuję być w stanie określić kodowanie bez łamania wstecznej zgodności. Gdybym miał użyć przeciążenia File.AppendAllText(filename, text, encoding), które kodowanie musiałbym określić, aby zapewnić, że pliki zostały utworzone w dokładnie taki sam sposób?

Odpowiedz

9

dwóch argumentów przeciążenie AppendAllText() kończy się wywołaniem metody wewnętrznej File.InternalAppendAllText() przy użyciu kodowania UTF-8 bez 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); 
} 

Dlatego można napisać:

using System.IO; 
using System.Text; 

File.AppendAllText(filename, text, new UTF8Encoding(false, true)); 
4

okiem na źródła pliku File.AppenAllText ujawniają następującą implementację:

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; 
    } 
} 

Wygląda więc na to, że chcesz przekazać wystąpienie kodu UTF8Encoding bez bajtów nagłówka UTF8.