C# Write File with Encoding


This entry is part 2 of 4 in the series C# Files Directories

This post is about encodings and the writing of text files from C#.

The code listing below writes three text files out to the D:\temp directory. Each file uses a different encoding. If you open each of these files in Notepad you will only see the letter A. In ASCII, the letter A is the number 65 and is this number in binary: 01000001. In binary, from the left to the right we have the following positions: 128, 64, 32, 16, 8, 4, 2, 1. The binary number 01000001 is 64 + 1 which equals 65.

Here is the C# code.

using System.Text;
using System.IO;

namespace WriteTextFile
{
    class Program
    {
        static void Main(string[] args)
        {
            var filenamewithpath = @"D:\temp\A_ascii.txt";
            File.WriteAllText(filenamewithpath, "A", Encoding.ASCII);
            filenamewithpath = @"D:\temp\A_unicode.txt";
            File.WriteAllText(filenamewithpath, "A", Encoding.Unicode);
            filenamewithpath = @"D:\temp\A_utf8.txt";
            File.WriteAllText(filenamewithpath, "A", Encoding.UTF8);
        }
    }
}

We can use a Hex Editor to see what is really inside each of these files. Even though all three files show the letter A, the bits underneath are all different! Encoding can become important when you need to output a file in a specific encoding. Some older legacy systems want to see only ASCII text, not Unicode text. for example. If you send them Unicode text they will throw an error. The name of the Hex Editor used in the screenshots is HxD Hex Editor by Mael Horz.



Bits

One important thing to notice is that the number of bits is 8 for ASCII, but is more for the other two.

The encoding options are:

  • ASCII
  • BigEndianUnicode
  • Default
  • Unicode
  • UTF32
  • UTF7
  • UTF8
Series Navigation<< C# FilesC# Filestream >>