错误字符串编码(Windows 10 + Visual Studio 2015 + Net 4.6)

lan*_*981 6 c# dictionary character-encoding visual-studio-2015 .net-4.6

我的代码:

Keys = new Dictionary<string, string>();
Keys.Add("?????_0", "raid_0");
Run Code Online (Sandbox Code Playgroud)

当我得到时Keys.ElementAt(0),我有这个:{[Íàáåã_0, raid_0]}.当然,当我运行程序时,key = "?????_0"没有定义,程序崩溃了System.Collections.Generic.KeyNotFoundException

当我使用Windows 8.1 + Visual Studio 2013 + net 3.5时,此代码工作正常

我该如何解决?

Han*_*ant 6

您以某种方式说服了C#编译器,您的源代码是在代码页1251(东欧和俄罗斯的默认系统代码页)中编写的.这通常是由于文本文件缺少utf-8 BOM造成的.不清楚这是怎么发生的,也许你用文本编辑器创建了文件,而不是Visual Studio内置的文本编辑器.也许它被源代码控制所破坏,具有Unix背景的那些倾向于丢弃BOM.

在Visual Studio中打开源文件并确保它仍然可以正确读取.然后使用文件>另存为,单击保存按钮上的箭头,选择"带编码"并选择"Unicode(带签名的UTF-8)".

还要确保默认值仍然良好.文件>高级保存选项>如有必要,请更改编码.如果您习惯使用其他文本编辑器,那么您需要对其进行配置,以便使用BOM保存文件.


Pav*_*kov 5

我有同样的问题,在我的情况下,ReSharper在应用"移动类到单独文件"重构后将文件保存在windows-1251中.

我已经使用此测试将repo中的所有cs文件转换为UTF-8.

    [Test]
    public void UpdateEncoding()
    {
        string path = @"C:\dev\Cash\src";
        foreach (var file in Directory.GetFiles(path, "*.cs", SearchOption.AllDirectories))
        {
            if (HasBom(file))
                continue;

            Console.WriteLine(file);

            var content = File.ReadAllText(file, Encoding.GetEncoding("windows-1251"));
            File.WriteAllText(file, content, Encoding.UTF8);
        }
    }

    private bool HasBom(string file)
    {
        using (var strm = new FileStream(file, FileMode.Open))
        {
            foreach (var b in Encoding.UTF8.GetPreamble())
            {
                if (strm.ReadByte() != b)
                    return false;
            }

            return true;
        }
    }
Run Code Online (Sandbox Code Playgroud)