0

What I need

Asp.net core app creates text files, whose encoding should match encoding of the hosting OS. This is because there is some legacy 3rd party software reading the files which can't handle UTF-8

What I have

The app is deployed to Windows Server, that is configured to use Windows-1250 charset.

I currently hardcoded it:

using var writer = new StreamWriter(fileStream, Encoding.GetEncoding("windows-1250"))

Question

How do I get host's OS's default encoding, so that I don't need to hardcode or configure it?

Liero
  • 25,216
  • 29
  • 151
  • 297
  • You can try to [detect OS](https://stackoverflow.com/questions/5116977/how-to-check-the-os-version-at-runtime-e-g-on-windows-or-linux-without-using) and encode accordingly. – Max Jul 12 '23 at 08:19
  • Looking at the [Remarks](https://learn.microsoft.com/en-us/dotnet/api/system.text.encoding.default?view=net-7.0#remarks) section, `Default` is out the window, right? – Fildor Jul 12 '23 at 08:20
  • @Max Encoding may not only depend on OS. The current default encoding for a given machine may not even be consistent over time (i.e. User could change settings to use a different encoding at any time). – Fildor Jul 12 '23 at 08:21
  • Consider switching to [UTF-8 Everywhere](https://utf8everywhere.org/)… – JosefZ Jul 12 '23 at 08:29
  • You could of course make it an AppSetting. Then it would be kind of semi-automatic. – Fildor Jul 12 '23 at 08:32
  • 1
    @Fildor-standswithMods: right, it can change, that's why I need to retrieve it. I've edited the "What I need" section with explanation why. – Liero Jul 12 '23 at 08:33
  • _"This is because there is some legacy 3rd party software reading the files which can't handle UTF-8"_ - wouldn't it be better to specifically set the specific encoding used by that 3rd party system? (Ignoring the fact that you would need to find _that_ out somehow, for now.) – Fildor Jul 12 '23 at 09:02
  • I suspect they don't use specific encoding, they use the OS setting. I can't imagine anybody would hardcode "Windows-1250" for reading files :O – Liero Jul 12 '23 at 13:05

0 Answers0