1 // Glyn Astill 09/02/2014
2 // Test to do conversion from DOS cp850 native through Latin1 to UTF8 and vice versa
5 using System.Collections.Generic;
8 using System.Threading.Tasks;
10 using System.Text.RegularExpressions;
16 private static Encoding _eCp850 = Encoding.GetEncoding(850);
17 private static Encoding _eUnicode = Encoding.UTF8;
18 private static Encoding _eLatin1 = Encoding.GetEncoding("ISO-8859-1");
20 public static string encode_cp850(string sText)
26 bSource = _eUnicode.GetBytes(sText);
27 bTarget = Encoding.Convert(_eUnicode, _eCp850, bSource);
28 sReturn = _eLatin1.GetString(bTarget);
33 public static string decode_cp850(byte[] sTextAsBytea)
36 byte[] bSource = sTextAsBytea;
39 bTarget = Encoding.Convert(_eCp850, _eUnicode, bSource);
40 sReturn = _eUnicode.GetString(bTarget);
45 static void Main(string[] args)
48 NpgsqlConnection conn;
49 NpgsqlTransaction tran;
50 NpgsqlCommand command;
53 conn = new NpgsqlConnection("Server=localhost;Port=5432;User Id=myuser;Password=mypassword;Database=mydatabase;Timeout=600;Pooling=false;ApplicationName=enctest");
55 tran = conn.BeginTransaction();
58 NpgsqlParameter add1 = new NpgsqlParameter("add1", NpgsqlTypes.NpgsqlDbType.Text);
59 command = new NpgsqlCommand("INSERT INTO myfile (add1) VALUES (:add1);", conn, tran);
60 add1.Value = encode_cp850("Schwanthaler Straße 75a");
62 command.Parameters.Add(add1);
63 command.ExecuteNonQuery();
66 //Read the data as bytea so as not to automatically convert into UTF-16
67 command = new NpgsqlCommand("select add1::bytea from myfile order by id desc limit 2;", conn, tran);
68 NpgsqlDataReader dr = command.ExecuteReader();
71 for (int i = 0; i < dr.FieldCount; i++)
73 // We now have bytea rather than string, but we can decode it easily enough
74 byte[] bSource = (byte[])dr[i];
75 String reEncodedString = decode_cp850(bSource);
76 Console.Write("Value: {0} \n", reEncodedString);
86 String keypress = Console.ReadLine().ToUpper();