c# - SqlDataReader:将 varbinary 读入字节数组

标签 c# sqldatareader varbinary varbinarymax

我有一个带有 varbinary(max) 列的 SQL Server 表。我用它来存储图像。使用 OpenFileDialog 选择图像,将其转换为 byte[],如下所示

public byte[] ConvertImageToByteArray(String filepath)
{
    try
    {
        return File.ReadAllBytes(filepath);
    }
    catch (Exception) 
    {
        throw; 
    }
}

然后使用这行代码将其存储到数据库中:

sqlCmd.Parameters.Add("@image", SqlDbType.VarBinary).Value = image;

它看起来像存储在数据库中,所以我想一切似乎都按预期工作。

enter image description here

不幸的是,我无法从数据表加载图像。

我正在使用 SqlDataReader 来执行此操作:

DbSql db = new DbSql();

SqlDataReader dr = db.GetDataReader(sqlCmd);

if (dr.Read())
{
    if (!dr.IsDBNull(1))
        productName = dr.GetString(1);

    if (!dr.IsDBNull(2))
        identNumber = dr.GetString(2);

    [...]

    if (!dr.IsDBNull(23))
        comment = dr.GetString(23);

    if (!dr.IsDBNull(24))
    {
        byte[] image = dr.GetSqlBytes(24).Value;  // <- This is where I try to grab the image
    }
}

似乎我无法使用

创建正确的 byte[]
image = dr.GetSqlBytes(24).Value;

因为我的下一步无法再次将其变成图像:

public Image ConvertImageFromByteArray(byte[] array)
{
        try
        {
            MemoryStream ms = new MemoryStream(array);
            return Image.FromStream(ms);
        }
        catch (Exception) { throw; }
    }

编辑: 当尝试类似的事情时 pictureBox.Image = ConvertImageFromByteArray(image) 我收到一条错误消息“无效参数”(自译,用德语说“Ungültiger Parameter”) enter image description here

谁能提供解决方案吗?

最佳答案

将 varbinary(MAX) 转换为字节数组后

image = (byte[])dr[24];

试试这个..

    MemoryStream ms = new MemoryStream(image);
    imagePictureBox.Image = System.Drawing.Image.FromStream(ms);

这就是我创建字节数组的方式...

    if (File.Exists(sLogoName) == false)
       throw new Exception("File Not Found: " + sLogoName);
    FileStream sourceStream = new FileStream(sLogoName, FileMode.Open, FileAccess.Read);
    int streamLength = (int)sourceStream.Length;
    Byte[] byLogo = new Byte[streamLength];
    sourceStream.Read(byLogo, 0, streamLength);
    sourceStream.Close();

关于c# - SqlDataReader:将 varbinary 读入字节数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51230564/

相关文章:

c# - 如何将自定义 header 添加到 SignalR 的 Typescript 客户端?

c# - 在反向代理后面部署 IdentityServer4

asp.net - 在 ASP.NET 中提取多个记录集时的 DataReader 或 DataSet

mysql - Reader 关闭时读取无效 (VB.Net)

php - Laravel varbinary(ip) 在不工作的地方使用

sql-server - 更新 VARBINARY(max) 列时 .WRITE(NULL, NULL, NULL) 的语义

c# - 如何将枚举转换为字节数组?

c# - ElasticSearch 索引映射和通配符

从 SqlDataReader 返回 Nullable 类型的 C# 性能提升

c# - 将时间序列模型与 PredictionEnginePool (ML.NET) 一起使用时 PredictionEngineBase 中出现异常