enumsystemcodepages (kernel32)
Last changed: anonymous

.
Summary

C# Signature:

[DllImport("kernel32.dll", SetLastError=true)]
static extern bool EnumSystemCodePages(EnumCodePagesProcDlgt lpCodePageEnumProc,
   uint dwFlags);
const uint CP_INSTALLED = 1;  // Enumerate only installed code pages
const uint CP_SUPPORTED = 2;  // Enumerate all supported code pages
delegate bool EnumCodePagesProcDlgt(string lpCodePageString);

User-Defined Types:

None.

Notes:

None.

Tips & Tricks:

I needed to enumerate the installed code pages on a Windows machine, and wanted to present the possible encoding interpretations to a user via a ComboBox. By using the Win32 API ::EnumSystemCodePages() via PInvoke, and the System.Text.Encoding.GetEncoding() static method, I could get the mapping from the code page to an Encoding instance which returns "pretty" names like 'Japanese (Shift-JIS)'.

Sample Code:

  class Class1
  {
    /// <summary>
    /// The main entry point for the application.
    /// </summary>
    [STAThread]
    static void Main(string[] args)
    {
      const uint CP_INSTALLED = 1;
      const uint CP_SUPPORTED = 2;

      EnumCodePagesProcDlgt dlgt = new EnumCodePagesProcDlgt(Class1.CodePageCallback);
      if (!EnumSystemCodePages(dlgt, CP_INSTALLED))
      {
    int errno = Marshal.GetLastWin32Error();
    Debug.WriteLine(string.Format("EnumSystemCodePages failed with errno = {0}", errno));
      }
    }

    private static bool CodePageCallback(string codePageString)
    {
      try
      {
    int cp = Convert.ToInt32(codePageString);
    Encoding enc = Encoding.GetEncoding(cp);
    Debug.WriteLine(string.Format("codePageString = '{0}' BodyName = '{1}' CodePage = {2} EncodingName = '{3}' HeaderName = '{4}' WindowsCodePage = {5}", codePageString, enc.BodyName, enc.CodePage, enc.EncodingName, enc.HeaderName, enc.WindowsCodePage));
      }
      catch (Exception err)
      {
    Debug.WriteLine(string.Format("ERROR: Failed to get encoding for '{0}'\n{1}", codePageString, err.Message));
      }
      return(true);
    }

    private delegate bool EnumCodePagesProcDlgt(string lpCodePageString);

    [DllImport("kernel32.dll", SetLastError=true)]
    private static extern bool EnumSystemCodePages(EnumCodePagesProcDlgt lpCodePageEnumProc, uint dwFlags);
  }

Alternative Managed API:

Do you know one? Please contribute it!

Documentation