Ensure UTF-8 is used for reading/writing files (backport 2.3.x)

Backport of #2838

Some merge conflicts.