I have a C# console application, and I was trying to do some ASCII art within it. However, some of the characters I wanted to use are Unicode. So, I was searching the intern
It turns out that there are multiple things you need to set up in order to make the console display Unicode characters.
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 to Lucida 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 that Console
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: