在 C# 中从 SQL Server 插入和检索 ByteArray

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/13952261/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-10 10:12:15  来源:igfitidea点击:

Insert and retrieve ByteArray from SQL Server in C#

c#

提问by coffeeak

I have a 128-bit key that I want to store in a database. My code creates the key as byte[16]and the datatype in the database is varbinary(16).

我有一个要存储在数据库中的 128 位密钥。我的代码创建密钥为byte[16],数据库中的数据类型为varbinary(16).

When I try to retrieve the byte array again from the db, I don't get the original values.

当我尝试从数据库中再次检索字节数组时,我没有得到原始值。

Here is my code:

这是我的代码:

byte[] test =  new byte[16]{0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15};

SqlCommand myInsertCmd = new SqlCommand("INSERT INTO Test(test) VALUES(@Param)", myConnection);       
SqlParameter param = myInsertCmd.Parameters.Add("@Param", SqlDbType.VarBinary, 16);
param.Value = test;

myInsertCmd.ExecuteNonQuery();

SqlDataAdapter myAdapter1 = new SqlDataAdapter("Select test from Test;", myConnection);
DataTable dt = new DataTable();
myAdapter1.Fill(dt);

foreach (DataRow row in dt.Rows)
{
    char[] charArray = row["test"].ToString().ToCharArray();
}

For charArray, I get 0x0053, 0x0079,0x0073,0x0074, etc and also, the charArrayis only 13 bytes long. What am I doing wrong?

对于charArray,我得到 0x0053、0x0079、0x0073、0x0074 等,而且charArray只有 13 个字节长。我究竟做错了什么?

采纳答案by Arsen Mkrtchyan

row["Test"]contains byte[], so row["Test"].ToString()returns default ToStringof byte[]type, which is "System.Byte[]". After which you convert System.Byte[]and get that result

row["Test"]包含byte[],所以row["Test"].ToString()返回默认ToStringbyte[]类型,这是"System.Byte[]"。之后你转换System.Byte[]并得到那个结果

foreach (DataRow row in dt.Rows)
{
    byte[] byteArray = (byte[])row["test"];
}