Hot To Convert String Encoding For Database Use?

September 4th, 2007 | by programming |

Sometimes when you try to input text into database from your C# applications, some of the characters don’t show up or show up differently. For Example: apostrophe(’) is very often replaced by question mark(?). The same thing happens when you try inserting chinese or japanese characters into database.

The reason of this is that the text is usually encoded in utf-8 and you have to convert it to unicode before inserting to database.

Following two methods converts input text from unicode to iso8859-1 and back. Use Iso8859_To_Unicode() method when inserting to database and Unicode_to_Iso8859 when getting the text from database.

public static string Iso8859_To_Unicode(string input) {
  Encoding iso = Encoding.GetEncoding(“iso8859-1″);
  Encoding unicode = Encoding.UTF8;
  byte[] isoBytes = iso.GetBytes(input);
  return unicode.GetString(isoBytes);
}
public static string Unicode_To_Iso8859(string input) {
  Encoding iso = Encoding.GetEncoding(“iso8859-1″);
  Encoding unicode = Encoding.UTF8;
  byte[] unicodeBytes = unicode.GetBytes(input);
  return iso.GetString(unicodeBytes);
}
  1. By val on Nov 20, 2007 | Reply

    Thanks, good tip!

  2. By irene on Nov 20, 2007 | Reply

    why use ISO8859-1? I have tried it, but can not work..why?

Post a Comment