As you know, strings in C # are all in Unicode. How to save a text file in the desired encoding?

Here is an example:

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

It creates a file, but with the encoding of the problem, it is definitely not ASCII. First thought, you need to convert the strings to ASCII before writing. excellent, take the example of MSDN, it turns out like this:

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

The output is also a file with an incomprehensible encoding. what don't i do wrong

    1 answer 1

    Your save code in ASCII works correctly - it saves Russian characters as? in ASCII encoding Russian letters not. Most likely you want to save in 1251:

     static void Main(string[] args) { string file = @"C:\Temp\test.txt"; string[] str = { "первая строка", "вторая строка", "последняя строка" }; using (StreamWriter writer = new StreamWriter(new FileStream(file, FileMode.OpenOrCreate), Encoding.GetEncoding(1251))) { foreach (string row in str) { writer.WriteLine(row); } } } 

    The same can be done in one line:

     File.WriteAllLines(file, str, Encoding.GetEncoding(1251)); 

    Recoding, as you do in the second example, can not be done. First, it tries to read the bytes of a string in Unicode as bytes of a string in ASCII. In the second, this code is applicable only if:

    • You already have a broken line - it was read from bytes indicating the wrong encoding
    • Code that reads it with the wrong encoding cannot be fixed.

    In all other cases, you just need to specify the encoding at the time of conversion from string to byte during writing and during the reverse reading.

    • thanks, everything is clear. - rawman