mike_pl
mike_pl

Reputation: 121

C# Write to file using StreamWriter with ANSI encoding doesn't work

I want to write to text file with ANSI encoding. Code looks like below:

string text = "abc123";
string filePath = "C:\\Data\\MyFile.csv";

using (StreamWriter sw = new StreamWriter(File.Open(filePath, FileMode.OpenOrCreate), Encoding.Default))
{
    sw.Write(text);
}

When I open result file with Notepad++ and click on 'Encoding' button on menu then there is always 'UTF-8 (without BOM)' which I want to avoid. I tried to choose option 'convert to ANSI', but after save of file and reopen it's still 'UTF-8.

I am stuck with this issue for long time, could anyone give some hint ?

Upvotes: 1

Views: 16119

Answers (2)

Run CMD
Run CMD

Reputation: 3035

If you export text containing special characters, for example 'é', Notepadd++ will then show the encoding as ANSI instead of UTF-8.

string text = "éçë";

Upvotes: 0

Alex Butenko
Alex Butenko

Reputation: 3764

There is no problem with StreamWriter, it is how Notepad++ works. You can easily see it yourself. Just open classic windows Notepad, type "test" and "save as" with ANSI encoding. Then open in Notepad++ - it will recognize encoding as UTF8.

Upvotes: 1

Related Questions