【发布时间】:2012-07-11 03:43:00
【问题描述】:
我正在使用 PostgreSQL 来驱动 C# 桌面应用程序。当我使用 PgAdmin 查询分析器更新带有特殊字符(如版权商标)的文本列时,它可以正常工作:
update table1 set column1='value with special character ©' where column2=1
当我在 C# 应用程序中使用相同的查询时,它会引发错误:
用于编码的字节序列无效
研究此问题后,我了解到 .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[])
-
正如我所解释的,encoder.getstring 也不起作用。顺便说一句,没有这样的功能可用 system.text.encoding.getstring.
-
不,我建议您使用 System.Text.Encoding.GetString 而不是 System.Text.Encoding.UTF8.GetString
-
.NET 4.0 中是否有 System.Text.Encoding.GetString 函数可用?我在这里错过了什么吗?它给出了编译错误。
-
我怀疑问题是您将数据库适配器错误配置为使用错误的编码(ANSI 左右)
标签: c# postgresql utf-8