Console.OutputEncoding set accordingly but Console still prints geeberish

前端 未结 1 964
慢半拍i
慢半拍i 2021-01-22 20:17

In debug I do see the characters properly. Why do Visual Studio and System.Console encodings differ ? How to make console\'s encoding match VS\'s one ?

There are a coupl

相关标签:
1条回答
  • 2021-01-22 20:22

    Here are the answers, finally:

    Why do Visual Studio and System.Console encodings differ ? How to make console's encoding match VS's one ?

    Answer: Setting System.Console.OutputEncoding to UTF8, Unicode or whatever else you need does the job. If the characters still keep being displayed incorrectly, the problem is with the font windows command prompt (what in VS we call Console) is configured to use not supporting the character set you are trying to display. In a short, the problem is then the font.

    I just could not find an answer (if even possible) to change the console's font.

    Answer: Here's a great link that will walk you through accomplishing such task.

    After adding additional fonts for display in the command prompt, this answer shows screenshots of how do select a newly added font.

    In a short, if you ended up in this post and are trying to have some non-ascii character set being printed in a command prompt window, the solution is setting System.Console.OuputEncoding accordingly + making sure the font configured to be used by your command prompt supports the character set you are dealing with.

    In addition - if you need the Console to support Right-To-Left printing, having found no built-in support, you can manually play with the cursor position, something like:

    private static void Main(string[] args)
    {
        Console.OutputEncoding = Encoding.Unicode;
    
        List<string> sentences = new List<string>();
    
        sentences.Add(string.Format("אברהם"));
        sentences.Add(string.Format("שורה {0}, אחרי אברהם", 2));
    
        foreach (var sentence in sentences)
        {
            WriteLineRTL(sentence);
        }
    }
    
    private static void WriteLineRTL(string input)
    {
        var chars = input.ToCharArray();
        Console.CursorLeft = chars.Length;
        for (int i = 0; i < chars.Length; i++)
        {
            Console.Write(chars[i]);
            Console.CursorLeft -= 2;
        }
        Console.WriteLine();
    }
    

    Output:

    0 讨论(0)
提交回复
热议问题