我正在使用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