我正在使用PostgreSQL爲C#桌面應用程序供電。當我使用pgAdmin的查詢分析器更新以特殊字符(如版權商標)文本列它的工作原理pefectly:c#中的UTF8字符串變量#
update table1 set column1='value with special character ©' where column2=1
當我使用這個相同的查詢從我的C#應用程序,它拋出一個錯誤:
invalid byte sequence for encoding
在研究了這個問題後,我知道.NET字符串使用UTF-16 Unicode編碼。
考慮:
string sourcetext = "value with special character ©";
// Convert a string to utf-8 bytes.
byte[] utf8Bytes = System.Text.Encoding.UTF8.GetBytes(sourcetext);
// Convert utf-8 bytes to a string.
string desttext = System.Text.Encoding.UTF8.GetString(utf8Bytes);
的問題,這裏既是sourcetext
和desttext
被編碼成UTF-16字符串。當我通過desttext
時,我仍然得到例外。
我也嘗試沒有成功如下:
Encoder.GetString, BitConverter.GetString
編輯:我甚至嘗試這樣做,不幫助:
unsafe
{
String utfeightstring = null;
string sourcetext = "value with special character ©";
Console.WriteLine(sourcetext);
// Convert a string to utf-8 bytes.
sbyte[] utf8Chars = (sbyte[]) (Array) System.Text.Encoding.UTF8.GetBytes(sourcetext);
UTF8Encoding encoding = new UTF8Encoding(true, true);
// Instruct the Garbage Collector not to move the memory
fixed (sbyte* pUtf8Chars = utf8Chars)
{
utfeightstring = new String(pUtf8Chars, 0, utf8Chars.Length, encoding);
}
Console.WriteLine("The UTF8 String is " + utfeightstring);
}
是否有一個數據類型在.NET中是支持存儲UTF-8編碼的字符串?是否有其他方法來處理這種情況?
可能是愚蠢的問題給你。但爲什麼不只是使用System.Text.Encoding.GetString(byte []) – HatSoft 2012-07-11 13:50:29
正如我解釋的encoder.getstring不工作。順便說一下,沒有這樣的函數可用system.text.encoding.getstring。 – Esen 2012-07-11 13:51:24
不,我建議你使用System.Text.Encoding.GetString不是System.Text.Encoding.UTF8.GetString – HatSoft 2012-07-11 13:52:55