2012-07-11 81 views
0

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

的问题,这里既是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编码的字符串?是否有其他方法来处理这种情况?

+0

可能是愚蠢的问题给你。但为什么不只是使用System.Text.Encoding.GetString(byte []) – HatSoft 2012-07-11 13:50:29

+0

正如我解释的encoder.getstring不工作。顺便说一下,没有这样的函数可用system.text.encoding.getstring。 – Esen 2012-07-11 13:51:24

+0

不,我建议你使用System.Text.Encoding.GetString不是System.Text.Encoding.UTF8.GetString – HatSoft 2012-07-11 13:52:55

回答

5

按照从单项目PostgreSQL他们认为这个页面,如果你有UTF8字符串错误,你可以设置编码的连接字符串中的Unicode(如果你使用的是Npgsql的驱动程序):

Encoding: Encoding to be used. Possible values: ASCII(default) and UNICODE. Use UNICODE if you are getting problems with UTF-8 values: Encoding=UNICODE

我一直在寻找正式的Npgsql文档,并没有提到。 NpgsqlConnection.ConnectionString

+0

为什么他们会使用ASCII作为默认-_- – CodesInChaos 2012-07-11 14:18:41

+0

感谢彼得,这似乎将工作。我会检查并接受它作为答案,如果它确实 – Esen 2012-07-11 14:19:03

+0

@Esen嗯,我从来没有使用postgresql,所以我不知道这是否真的能解决你的问题 - 但它似乎确实是合理的。 – 2012-07-11 14:22:47

-1

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

+0

我缩小了这个问题。此查询在查询分析器中工作,而不是通过代码。你能解释一下吗?更新table1设置column1 ='©'其中column2 = 1 – Esen 2012-07-11 14:11:33

-1

只要把你的ConnectionString就结束了“......;统一=真正的”

+0

我已经想出了答案,在Peter M的回答中评论道。你为什么再次复制。 – Esen 2014-01-27 16:14:05