[英]UTF8 string variable in c#
我正在使用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编码的字符串? 是否有其他方法可以处理这种情况?
按照Mono项目PostgreSQL上的此页面,他们建议,如果您对UTF8字符串有错误,则可以在连接字符串中将编码设置为unicode(如果您使用的是Npgsql驱动程序):
编码:要使用的编码。 可能的值:ASCII(默认)和UNICODE。 如果您在使用UTF-8值时遇到问题,请使用UNICODE:Encoding = UNICODE
而且我一直在寻找官方的Npgsql文档,但没有提及。 NpgsqlConnection.ConnectionString
我认为这可能不是由utf-8或16引起的,也可能是由特殊字符引起的,您可以将char替换为类似于'&amp';的实体char。
只需在您的ConnectionString的末尾加上一个“ ......; Unicode = true”
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.