Error string encoding (Windows 10 + Visual Studio 2015 + Net 4.6)

♀尐吖头ヾ 提交于 2019-12-05 06:58:41

You somehow convinced the C# compiler that your source code was written in code page 1251, the default system code page in Eastern Europe and Russia. That's usually caused by the text file missing the utf-8 BOM. Unclear how this happened, maybe you created the file with a text editor other than the one built into Visual Studio. Maybe it got mangled by source control, the ones with a Unix background tend to drop the BOM.

Open the source file in Visual Studio and ensure it still reads correctly. Then use File > Save As, click the arrow on the Save button, select "with encoding" and pick "Unicode (UTF-8 with signature)".

Also make sure that the default is still good. File > Advanced Save Options > change the Encoding if necessary. If you habitually use another text editor then you'll want configure it so it saves files with a BOM.

I have the same issue, in my case it was ReSharper who saved my files in windows-1251 after applying "move class to separate file" refactoring.

I've used this test to convert all my cs files in repo to 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;
        }
    }

This is a known bug in Visual Studio 2015 Relase version. See https://github.com/dotnet/roslyn/issues/4022. It is already fixed and will be available in next version of toolset (1.1)

If you don't want to change source code encoding, you can add encoding element into .csproj file. This helped for me (added into <PropertyGroup> element):

<CodePage>1250</CodePage>

But of course just a temporary hack, useless for solutions with many projects.

I am also having this issue with a local project that worked perfectly in Win8.1/VS2013. So this is not related with TFS or any other repository. Resaving to UTF-8 helps. Also, I have a Russian localized Visual Studio that was updated to English by language pack (hate localized IDE and MSDN).

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