Search code examples
c#textcharacter-encoding

When writing text file how to force ANSI format in C#?


How can I write a text file in ANSI format using C# on Windows 10 so that it is displayed as ANSI (not UTF-8) when opened in Notepad or Notepad++? Currently, my code produces a file that is displayed as UTF-8, but I want the bottom-right corner of Notepad++ or Notepad to show "ANSI" when opening the file. Below is the code I’ve tried:

private void createHeader()
        {
            StringBuilder sb = new StringBuilder();
            string delimiter = "ª";

            sb.Append(batchNumber);
            sb.Append(delimiter);
            sb.Append("Delete PLUs");
            sb.Append(delimiter);

            string today = DateTime.Now.ToString("MM/dd/yyyy hh:mm:ss tt");
            //Console.WriteLine(today);
            sb.Append(today);

            for (int i =0; i < 15; i++)
            {
                sb.Append(delimiter);
            }

            sb.Append(Environment.NewLine);

            Console.WriteLine(sb.ToString());

            System.IO.StreamWriter objWriter;
            objWriter = new System.IO.StreamWriter(new FileStream(pathToFile, FileMode.OpenOrCreate), Encoding.ASCII);
            objWriter.WriteLine(sb.ToString());
            objWriter.Close();
            //System.IO.File.WriteAllText(pathToFile, sb.ToString(), Encoding.ASCII); // Erases current file and overwrite

            //return sb.ToString();
        }

Solution

  • Use encoding 1252.

    using (TextWriter tw = new StreamWriter(pathToFile, true, Encoding.GetEncoding(1252)))
    {
              tw.WriteLine(sb.ToString());
    }