How to write Unicode characters to the console?

别来无恙 提交于 2019-12-11 06:53:48

问题


I was wondering if it was possible, in a console application, to write characters like using .NET. When I try to write this character, the console outputs a question mark.


回答1:


It's likely that your output encoding is set to ASCII. Try using this before sending output:

Console.OutputEncoding = System.Text.Encoding.UTF8;

(MSDN link to supporting documentation.)

And here's a little console test app you may find handy:

C#

using System;
using System.Text;

public static class ConsoleOutputTest {
    public static void Main() {
        Console.OutputEncoding = System.Text.Encoding.UTF8;
        for (var i = 0; i <= 1000; i++) {
            Console.Write(Strings.ChrW(i));
            if (i % 50 == 0) { // break every 50 chars
                Console.WriteLine();
            }
        }
        Console.ReadKey();
    }
}

VB.NET

imports Microsoft.VisualBasic
imports System

public module ConsoleOutputTest 
    Sub Main()
        Console.OutputEncoding = System.Text.Encoding.UTF8
        dim i as integer
        for i = 0 to 1000
            Console.Write(ChrW(i))
            if i mod 50 = 0 'break every 50 chars 
                Console.WriteLine()
            end if
        next
    Console.ReadKey()
    End Sub
end module

It's also possible that your choice of Console font does not support that particular character. Click on the Windows Tool-bar Menu (icon like C:.) and select Properties -> Font. Try some other fonts to see if they display your character properly:




回答2:


I found some elegant solution on MSDN

System.Console.Write('\uXXXX') //XXXX is hex Unicode for character

This simple program writes ℃ right on the screen.

using System;

public class Test
{
    public static void Main()
    {
        Console.Write('\u2103'); //℃ character code
    }
}



回答3:


Console.OutputEncoding Property

http://msdn.microsoft.com/library/system.console.outputencoding(v=vs.110).aspx

Note that successfully displaying Unicode characters to the console requires the following:

  • The console must use a TrueType font, such as Lucida Console or Consolas, to display characters



回答4:


Besides Console.OutputEncoding = System.Text.Encoding.UTF8;

for some characters you need to install extra fonts (ie. Chinese).

In Windows 10 first go to Region & language settings and install support for required language:

After that you can go to Command Prompt Proporties (or Defaults if you like) and choose some font that supports your language (like KaiTi in Chinese case):

Now you are set to go:



来源:https://stackoverflow.com/questions/55224030/differences-between-computers-in-json-returned-for-serialized-c-sharp-objects

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!