Click here to Skip to main content
15,891,607 members
Articles / Programming Languages / C#
Tip/Trick

How to Get a File's Encoding with C#

Rate me:
Please Sign up or sign in to vote.
3.39/5 (9 votes)
21 Feb 2018CPOL 48.6K   13   5
This article describes how to get a file's encoding with C#

Introduction

This tip describes how to get a file's encoding with C#.

Background

For some reason, it took me a while to figure it out. All the forums and discussions I found did not have the exact correct way (meaning when I tried to use them, I got wrong results). Although some came very close...

Using the Code

Simply copy paste.

C#
/// <summary
/// Get File's Encoding
/// </summary>
/// <param name="filename">The path to the file
private static Encoding GetEncoding(string filename)
{
    // This is a direct quote from MSDN:  
    // The CurrentEncoding value can be different after the first
    // call to any Read method of StreamReader, since encoding
    // autodetection is not done until the first call to a Read method.

    using (var reader = new StreamReader(filename, Encoding.Default, true))
    {
        if (reader.Peek() >= 0) // you need this!
            reader.Read();

        return reader.CurrentEncoding;
    }
}

Points of Interest

The key to making it work was hidden in the remarks section in MSDN: only after performing a read, we will have the correct CurrentEncoding value.

I hope this helps!

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Chief Technology Officer Alpha Beta
Israel Israel
Adi Eduard is a software developer for the last 10 years.
Experienced with management, design, development and deployment of software projects.
Dedicated to the task at hand, works well in a team and has a passion for technology and innovation

Comments and Discussions

 
QuestionThis code is unreliabe because it only detects BOM Pin
jachrist17-Dec-22 3:08
jachrist17-Dec-22 3:08 
QuestionThis only works with BOM files. Pin
Veli V19-Mar-20 21:00
Veli V19-Mar-20 21:00 
QuestionAnother (more complicated) method ... Pin
RenniePet25-Feb-18 12:54
RenniePet25-Feb-18 12:54 
AnswerRe: Another (more complicated) method ... Pin
Adi Eduard7-Mar-18 0:36
Adi Eduard7-Mar-18 0:36 
QuestionThanks for sharing this Pin
LightTempler21-Feb-18 7:46
LightTempler21-Feb-18 7:46 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.