0

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

这里的问题是sourcetextdesttext都被编码为 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 编码字符串的数据类型?是否有其他方法来处理这种情况?

4

3 回答 3

5

根据来自 mono 项目PostgreSQL的这个页面,他们建议如果您在使用 UTF8 字符串时遇到错误,您可以在连接字符串中将编码设置为 unicode(如果您使用的是 Npgsql 驱动程序):

编码:要使用的编码。可能的值:ASCII(默认)和 UNICODE。如果遇到 UTF-8 值问题,请使用 UNICODE:Encoding=UNICODE

而且我一直在查看官方 Npgsql 文档,但没有提及。 NpgsqlConnection.ConnectionString

于 2012-07-11T14:14:56.447 回答
-1

我认为它可能不是由 utf-8 或 16 引起的,它可能是由 de 特殊字符引起的,您可以将 char 替换为实体 char,例如 '&';

于 2012-07-11T14:08:00.193 回答
-1

只需在您的 ConnectionString 末尾添加一个“...... ;Unicode=true”

于 2014-01-21T22:16:51.143 回答