-1

我有一个客户端/服务器架构,其中交换文本格式的消息。

例如:

12  2013/11/11  abcd  5
^     ^          ^    ^
int  date      text  int

一切都适用于“正常”文本。现在这是一个中文项目,所以他们也想发送中文符号。编码 GB18030 或 GB2312。

我这样读取数据:

char[] dataIn = binaryReader.ReadChars(length);

然后我从 char 数组创建一个新字符串并将其转换为正确的数据类型(int、float、string 等)。

如何更改/启用中文编码,或将字符串值转换为中文?什么是测试这个的好方法。谢谢。

我尝试使用这样的东西

string stringData = new string(dataIn).Trim();
byte[] data = Encoding.Unicode.GetBytes(stringData);
stringData = Encoding.GetEncoding("GB18030").GetString(data);

没有成功。

我还需要将一些文本值保存到 MS SQL Server 2008,这可能吗 - 我需要配置什么特别的东西吗?

我还尝试了将这个示例存储到数据库并打印到控制台,但我只是得到 ????????

string chinese = "123东北特钢大连新基地testtest"; 
byte[] utfBytes = Encoding.Unicode.GetBytes(chinese); 
byte[] chineseBytes = Encoding.Convert(Encoding.Unicode, Encoding.GetEncoding("GB18030"), utfBytes); 
string msg = Encoding.GetEncoding("GB18030").GetString(chineseBytes);

编辑 问题出在我发送到数据库的 INSERT 查询上。我在字符串之前使用 N' 来修复它。

sqlCommand = string.Format("INSERT INTO uber_chinese (columnName) VALUES(N'{0}')", myChineseString);

列 dataType 也必须是 nvarchar 而不是 varchar。

4

1 回答 1

1

这个分析器是由我自己的评论“提升”的(应原始海报的要求)。

在 .NET Framework 中,字符串已经是 Unicode 字符串。

(不过,不要通过写入控制台来测试 Unicode 字符串,因为终端窗口和控制台通常不会正确显示它们。但是,由于 .NET 版本 4.5 对此有一些支持。)

要注意的是Encoding当您从外部来源获取文本时。在这种情况下, 的构造函数BinaryReader提供了一个重载,它接受Encoding

using (var binaryReader = new BinaryReader(yourStream, Encoding.GetEncoding("GB18030")))
    ...

On the SQL Server, be sure that any column that needs to hold Chinese strings is of type nvarchar (or nchar), not just varchar (char). Otherwise, depending on the collation, the column may not be able to hold general Unicode characters (it may be represented internally by some 8-bit Microsoft code page).

Whenever you give an nchar literal in SQL, use the format N'my text', not just 'my text', to make sure the literal is interpreted as an nchar rather than just char. For example N'Erdős' is distinct from N'Erdos' while, in many collations, 'Erdős' and 'Erdos' might be (projected onto) the same value in the underlying code page.

Similarly N'东北特钢大连新基地' will work, while '东北特钢大连新基地' might result in a lot of question marks. From the update of your quetion:

sqlCommand = string.Format("INSERT INTO uber_chinese (columnName) VALUES(N'{0}')", myChineseString);
                                                                         ↑

(This is prone to SQL injection, of course.)

The default collation of your column will be that of your database (SQL_Latin1_General_CP1_CI_AS from your comment). Unless you ORDER BY that column, or similar, that will probably be fine. If you do order by this column, consider using some Chinese language collation for the column (or for the entire database).

于 2013-06-04T15:49:56.747 回答