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