c# - 将非英文字符输入 C# 控制台应用程序时出现的问题

标签 c# visual-studio-2010 unicode console-application

我正在尝试在英文版 Windows 7 Ultimate 64 位上使用 Visual Studio 2010 构建控制台 C# 应用程序。当我尝试复制带有非 ASCII 字符的路径,然后将其粘贴到我的控制台应用程序时,非 ASCII 字符变成了 ???。有什么办法可以解决这个问题吗?

这是我正在复制的内容:C:\Test Folder\документи

这是代码(在上面建议的链接之后):

Console.OutputEncoding = System.Text.Encoding.UTF8;
string strLineUserInput = Console.ReadLine();

但即使我更改字体,C:\Test Folder\документи 仍然变成 C:\Test Folder\??????????当我用调试器测试它时,在 strLineUserInput 变量中。

另请注意,与链接“重复帖子”不同,我需要在输入中使用这些字符。

所以如果我这样做的话:

Console.InputEncoding = System.Text.Encoding.UTF8;
string strLineUserInput = Console.ReadLine();

如果我阅读上面的文本,我的 strLineUserInput 将变为 null

最佳答案

请按照以下步骤操作:

  1. 在调试/不调试时将控制台窗口字体更改为 Lucida Console
  2. 执行以下代码:

    public static void Main(String[] args)
    {
        Console.OutputEncoding = System.Text.Encoding.GetEncoding("Cyrillic");
        Console.InputEncoding = System.Text.Encoding.GetEncoding("Cyrillic");
    
        Console.WriteLine(@"C:\Test Folder\документи");
        // input C:\Test Folder\документи
        string strLineUserInput = Console.ReadLine();
        Console.WriteLine(strLineUserInput);
    }
    

输出应该是:

C:\Test Folder\документи
C:\Test Folder\документи
C:\Test Folder\документи

[更新]

也许您想使用 ReadKey 方法来让它工作(您仍然必须使用 Lucida Console 字体):

static void Main(string[] args)
{
    Console.OutputEncoding = Encoding.UTF8;
    Console.InputEncoding = Encoding.UTF8;

    string s = @"C:\Test Folder\документи";
    Console.WriteLine(s);

    // input C:\Test Folder\документи
    var strInput = ReadLineUTF();

    Console.WriteLine(strInput);
}

static string ReadLineUTF()
{
    ConsoleKeyInfo currentKey;

    var sBuilder = new StringBuilder();
    do
    {
        currentKey = Console.ReadKey();
        // avoid capturing newline
        if (currentKey.Key != ConsoleKey.Enter)
            sBuilder.Append(currentKey.KeyChar);

    }
    // check if Enter was pressed
    while (currentKey.Key != ConsoleKey.Enter);

    // move on the next line
    Console.WriteLine();

    return sBuilder.ToString();
}

关于c# - 将非英文字符输入 C# 控制台应用程序时出现的问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14969840/

相关文章:

c# - 如何进行服务器端 C# SQL 验证

c# - 寻找网格岛的外边缘

android - 如何在 Android 资源中使用 unicode?

java - 如何在java中创建多行正则表达式-越界异常

C# 在静态字典中存储值

visual-studio - VS 2008 或 2010 Express 版本是否附带任何可用的控制台 http 下载实用程序?

asp.net - 当我停止调试时,Visual Studio 会删除 cookie

visual-studio-2010 - 在 Visual Studio 的包管理器控制台中使用 git

.net - 如何从字符串中间执行区分区域性的 "starts-with"操作?

c# - 当使用 Directory.Move 时该文件已存在时无法创建该文件