C# 中的 GetBytes 未返回正确的值

本文关键字:返回 中的 GetBytes | 更新日期: 2023-09-27 18:37:19

我有一个执行存储过程并返回该存储过程值的方法。我有一个 VIN 在 SQL 中是VarBinary类型。我不确定我可以使用什么来获取值。

这是我的代码:

    // Get Customer Product By CustomerID
    public Model.CustomerProduct Get_CustomerProduct(int Customer_ID)
    {
        Model.CustomerProduct model = null;
        string myConnection = System.Configuration.ConfigurationManager.ConnectionStrings[connectionName].ToString();
        SqlDatabase db = new SqlDatabase(myConnection);
        int bufferSize = 100;                   
        byte[] outByte = new byte[bufferSize];  
        using (DbCommand command = db.GetStoredProcCommand("Get_Customer_Product"))
        {
            db.AddInParameter(command, "Customer_ID", DbType.Int32, Customer_ID);
            var result = db.ExecuteReader(command);
            try
            {
                if (result.FieldCount == 0)
                    model = null;
                else
                {
                    result.Read();
                    model = new Model.CustomerProduct()
                    {
                       Product_Name = result.GetString(2)
                      ,VIN =result.GetBytes(3,0,outByte,0,bufferSize)   // this return me wrong 

                    };
                }
            }
            catch (Exception ex)
            {

            }
            return model;
        }
    }

我的问题是这一行:

     VIN =result.GetBytes(3,0,outByte,0,bufferSize) 

这返回 44,但假设返回的值是:

0x00D1CCE9771AE7554D479F7B93A45611010000004158D130E5097EF2924DEC4C6255E5BAF4C8EF4C2AC2A8FD9F29295F41DA3550123C6C4575788F5E6

C# 中的 GetBytes 未返回正确的值

GetBytes 方法返回它已写入数组的字节数,而不是字节本身。看看outByte的内容,你应该在那里找到你的数据。

我还建议您首先使用空缓冲区调用GetBytes。这将导致它返回字段的长度,从而允许您正确调整缓冲区的大小:

int len = result.GetBytes( 3, 0, null, 0, 0 );
byte[] buf = new byte[len];
result.GetBytes( 3, 0, buf, 0, buf.Length );
model = new Model.CustomerProduct()
{
    Product_Name = result.GetString(2),
    VIN = buf
};

如果您现在运行的代码,则很可能还必须将VIN类型更改为byte[]

GetBytes 返回读取的字节数。由于您正在将 Getbytes 返回值分配给 VIN ,因此您会看到在 VIN 中读取的字节数。

相反,您必须从输出缓冲区读取,即在您的情况下,outByte 将具有读取的字节。