Reputation: 330
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! :-(
Upvotes: 2
Views: 4647
Reputation: 9704
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);
Upvotes: 6