Как известно строки в С# все в Unicode. Как сохранить текстовый файл в нужной кодировке ?
Вот такой пример:
static void Main(string[] args)
{
string file = @"C:\Temp\test.txt";
string[] str = { "первая строка", "вторая строка", "последняя строка" };
using (StreamWriter writer = new StreamWriter(new FileStream(file, FileMode.OpenOrCreate), Encoding.ASCII))
{
foreach (string row in str)
{
writer.WriteLine(row);
}
}
}
Создает файл, но с кодировкой проблемы, она точно не ASCII. Первая мысль, нужно строки преобразовать в ASCII перед записью. отлично, беру пример с MSDN, получается так:
static void Main(string[] args)
{
string file = @"C:\Temp\test.txt";
string[] str = { "первая строка", "вторая строка", "последняя строка" };
using (StreamWriter writer = new StreamWriter(new FileStream(file, FileMode.OpenOrCreate), Encoding.ASCII))
{
foreach (string row in str)
{
writer.WriteLine(UnocodeToASCII(row));
}
}
}
private static string UnocodeToASCII(string source)
{
// Create two different encodings.
Encoding ascii = Encoding.ASCII;
Encoding unicode = Encoding.Unicode;
// Convert the string into a byte array.
byte[] unicodeBytes = unicode.GetBytes(source);
// Perform the conversion from one encoding to the other.
byte[] asciiBytes = Encoding.Convert(unicode, ascii, unicodeBytes);
// Convert the new byte[] into a char[] and then into a string.
char[] asciiChars = new char[ascii.GetCharCount(asciiBytes, 0, asciiBytes.Length)];
ascii.GetChars(asciiBytes, 0, asciiBytes.Length, asciiChars, 0);
return new string(asciiChars);
}
На выходе тоже файл с непонятной кодировкой. что не я делаю не так?