2

This is driving me insane. I want to read a number of text files (located outside my project directory), encoded with Windows-1252, edit them as strings, and write back to those files, again as Windows-1252. Yet Visual Studio keeps churning out UTF-8 files instead.

Here's my file reading code:

using (StreamReader sr = new StreamReader(fileName, Encoding.Default))
{
    String s = sr.ReadToEnd();
    return s;
}

Here is my file writing code:

File.WriteAllText(fileName, joinedFileString, Encoding.Default);

In between these two I perform various edits, including adding, removing, and grepping linebreaks, but I presumed that those would be resolved in the proper encoding by specifying the encoding in File.WriteAllText. Note that I have, in the Advanced Save Options of Visual Studio, changed the default encoding to 1252. So Encoding.Default should refer to the proper one.

Yet it keeps turning files into UTF-8! :-(

KeizerHarm
  • 330
  • 1
  • 4
  • 22
  • 2
    You probably shouldn't use `Encoding.Default` to target a specific encoding. I don't think the Visual Studio settings would affect this, while system settings would. Does `Encoding.GetEncoding(1252)` work in it's place? – Jonathon Chase May 24 '18 at 20:10
  • @JonathonChase Thanks, but I tried that. I get ``"No data is available for encoding 1252. For information on defining a custom encoding, see the documentation for the Encoding.RegisterProvider method."`` – KeizerHarm May 24 '18 at 20:12
  • 1
    You may want to look at the answer to [this question](https://stackoverflow.com/questions/49215791/vs-code-c-sharp-system-notsupportedexception-no-data-is-available-for-encodin) regarding the encoding error you receive. – Jonathon Chase May 24 '18 at 20:17
  • ...that actually worked. I cannot believe it. – KeizerHarm May 24 '18 at 20:20
  • Do you want to put it as an answer, so I can Accept it? – KeizerHarm May 24 '18 at 20:20

1 Answers1

6

You will want to specify the encoding you are using more explicitly. Encoding.Default may vary from system to system, and according to the documentation,

the default encoding can even change on a single computer.

Since you know which encoding you want, you can specify it specifically with Encoding.GetEncoding(1252)

In some environments, you may need to register a provider for the available encodings. You can do this by adding the System.Text.Encoding.CodePages nuget package to your project and registering it with Encoding.RegisterProvider(CodePagesEncodingProvider.Instance);

Jonathon Chase
  • 9,396
  • 21
  • 39