Set C# console application to Unicode output
It turns out that there are multiple things you need to set up in order to make the console display Unicode characters.
- Set the console to a Unicode supported font. To do this, run your C# console application once with
Console.ReadKey();
so the window stays open. Right click on the title bar of the window and select Properties. These options will persist when debugging through Visual Studio. You might need to use the Default menu instead for persisting the options throughout the system. In the Fonts tab, you need to set the font toLucida Console
. This font supports Unicode characters. The related post can be found here. Set the console's code page to UTF-8. This one is a bit tricky. Because, you have to execute a command in the console window to change the code page. For whatever reason, this option is not available as a console preference. To do this, you'll need to make a separate
cmd.exe
process, and use this instead of the normal console provided.var cmd = new Process { StartInfo = { FileName = "cmd.exe", RedirectStandardInput = true, RedirectStandardOutput = true, CreateNoWindow = true, UseShellExecute = false } }; cmd.Start(); cmd.StandardInput.WriteLine("chcp 65001"); cmd.StandardInput.Flush(); cmd.StandardInput.Close();
The first part of the code above will create a new
cmd.exe
process. The settings given to StartInfo will make sure thatConsole
is redirected to this new process. The second part of the code sends a command to this console window and runs it. That command,chcp 65001
, sets the console's code page to UTF-8. Related posts can be found here and here.Set the OutputEncoding to UTF-8. This is the only way that
Console.WriteLine
will actually output Unicode characters. Setting this is very simple.Console.OutputEncoding = Encoding.UTF8;
Now, any output from
Console
will be in Unicode. The related post can be found here.
So, that's it! I hope this information helps someone. :-)
Another option is to use P/Invoke to change the code page directly:
class Program
{
[DllImport("kernel32.dll", SetLastError = true)]
private static extern bool SetConsoleOutputCP(uint wCodePageID);
[DllImport("kernel32.dll", SetLastError = true)]
private static extern bool SetConsoleCP(uint wCodePageID);
static async Task<int> Main(string[] args)
{
SetConsoleOutputCP(65001);
SetConsoleCP(65001);
Console.WriteLine("This is how you say hello in Japanese: こんにちは");
return 0;
}
}
Output: