Convert Utf 8 String To Windows Cp 1258

I want to convert a text file from utf-8 to windows cp-1258 by C# console, here is my code but it does not work, the output file content is not cp-1258

string path = @"E:\mp4\test\Cyborg.txt";
string readText = File.ReadAllText(path);
Encoding vnmese = Encoding.GetEncoding("windows-1258");
Encoding utf8 = Encoding.UTF8;
byte[] utfBytes = utf8.GetBytes(readText);
byte[] vnBytes = Encoding.Convert(utf8, vnmese, utfBytes);
string msg = vnmese.GetString(vnBytes);
string path2 = @"E:\mp4\test\MyTest.txt";
File.WriteAllText(path2, msg, vnmese);

Any help would be much appreciated

Jon Skeet
people
quotationmark

Your current code is going through all kinds of steps it doesn't need to. All you need is:

string text = File.ReadAllText("input.txt");
Encoding encoding = Encoding.GetEncoding(1258);
File.WriteAllText("output.txt", text, encoding);

That's far easier to understand, and should work fine.

However, as far as I can see, your code should already work - which suggests one of three options:

  • Your original text file isn't in UTF-8
  • Your expectations of a file in Windows-1258 are invalid
  • Your file contains text that can't be represented in Windows-1258

people

See more on this question at Stackoverflow