How can I determine using .Net (C# or which encoding used in a Text file


How can I determine using .Net (C# or which encoding used in a Text file?

I have a text file in either unicode or utf8 or ascii and I need to determine which encoding the file is written in. The solution of using BOM to verify the encoding dosn't work as not all text files have a BOM.

It would be great if i could get a sample code for this.

Who is Participating?
Jacques Bourgeois (James Burger)Connect With a Mentor PresidentCommented:
If you use the StreamReader to read the file, it has a constructor that calls for a String and a Boolean. If you set the Boolean to True, it will detect the encoding for you if the file follows the proper coding conventions (the first 3 bits should identify the encoding).

You can then read the CurrentEncoding property to know which encoding was detected.

There is code that does that in the documentation for the StreamReader.CurrentEncoding Property.
dm_teamAuthor Commented:
Thanks for the comment. I checked the code. Sorry to say that its not working.
Éric MoreauSenior .Net ConsultantCommented:
can I ask you why?
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.