NotSupportedException: No data is available for encoding 1252

Another day, another surprise on .NET Core. Tried to load a file with Windows-1252 encoding and got the following exception: NotSupportedException: No data is available for encoding 1252. For information on defining a custom encoding, see the documentation for the Encoding.RegisterProvider method. Here’s how to solve the problem.

Adding missing encodings

It turns out that some “exotic” encodings (including popular Windows-1252) are defined in separate NuGet package and these encodings are not available by default.

Solution is simple. Add System.Text.Encoding.CodePages NuGet package to solution and use the following piece of code in application startup class to registester new encodings.

public void ConfigureServices(IServiceCollection services)

    // more code here

Changing encoding of text

Now let’s convert file in Windows-1252 encoding to UTF-8.

var path = "c:\\temp\\observations.txt";

var estEncoding = Encoding.GetEncoding(1252);
var est= File.ReadAllText(path, estEncoding);                             
var utf = Encoding.UTF8;
est = utf.GetString(Encoding.Convert(estEncoding, utf, estEncoding.GetBytes(est)));

Important thing in the code above is using Windows-1252 encoding when reading contents of file. With out specifying encoding it is expected that file is in UTF-8 already.

Liked this post? Empower your friends by sharing it!
Categories: .NET ASP.NET

View Comments (2)

  • Ido not understand the explanation, because these explanations are clearly meant for c and not the basic variant of the system.

    Equivalent VB code would be nice as wall as instruction where to place the précisely to place the code.



Related Post