Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Specify encoding when reading file from Resource

Tags:

c#

.net

I have an UTF8 file, which I have added to my project in Resources.resx, called Template.txt

If I read the file normally like this:

string template = File.ReadAllText(@"filepath\Template.txt", Encoding.UTF8);

Everything works fine.

However if I read it like this:

string template = Properties.Resources.Template

It is filled with Japanese characters, and thus has the wrong encoding.

byte[] bytes = Encoding.Default.GetBytes(Properties.Resources.Template);
string template = Encoding.UTF8.GetString(bytes);

This also still gives Japanese characters.

Does anyone know the cause? If I just double click the Template.txt file in Visual Studio, I can just read it normally also.

like image 300
Red Riding Hood Avatar asked Sep 30 '16 11:09

Red Riding Hood


Video Answer


2 Answers

As Hans Passant said in the comments, encoding the file so that it includes the UTF-8 BOM (Byte Order Mark) fixed the issue.

like image 61
Red Riding Hood Avatar answered Oct 19 '22 17:10

Red Riding Hood


In VS, select the Resources.resx file, then go File > Save Resources.resx As...

and Save with Encoding... and select Unicode(UTF-8 without signature) - Codepage 65001 and OK.

like image 42
Joel Wiklund Avatar answered Oct 19 '22 17:10

Joel Wiklund