【问题标题】:UTF8 string variable in c#c#中的UTF8字符串变量
【发布时间】: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);

这里的问题是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 编码字符串的数据类型?有其他方法可以处理这种情况吗?

【问题讨论】:

  • 对你来说可能是个愚蠢的问题。但为什么不直接使用 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


【解决方案1】:

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

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

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

【讨论】:

  • 他们为什么默认使用 ASCII -_-
  • 谢谢彼得,这似乎可行。如果有,我会检查并接受这个作为答案
  • @Esen 好吧,我从未使用过 postgresql,所以我不知道这是否真的能解决您的问题 - 但它看起来确实合理。
  • forums.devart.com/… 这个链接也是类似的。我正在尝试在 web.config 中设置 unicode=true 并查看是否可行。您的回答向我展示了前进的道路。
  • 是的,它有效。我必须在连接字符串中设置 Unicode=true。感谢彼得帮助解决了这个问题。
【解决方案2】:

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

【讨论】:

  • 我缩小了问题的范围。此查询在查询分析器中工作,而不是通过代码。你能解释一下吗?更新 table1 设置 column1='©' where column2=1
【解决方案3】:

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

【讨论】:

  • 我已经找到了答案,在 Peter M 的回答中发表了评论。你为什么又重复那个。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-03-30
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多