无法将类型为“System.Byte[]”的对象强制转换为类型“System.String[]”

本文关键字:System 类型 转换 String 对象 Byte | 更新日期: 2023-09-27 18:35:27

您好,我正在尝试传递从Byte[]转换为String[] image并以ReportViewer Image显示它,如下所示:

String[] dataImage;
private void showLogo()
{
    try
    {
        SqlDataAdapter dataAdapter = new SqlDataAdapter( new SqlCommand("SELECT logo
                                           FROM company WHERE id = 1", spojeni));
        DataSet dataSet = new DataSet();
        dataAdapter.Fill(dataSet);
        if (dataSet.Tables[0].Rows.Count == 1)
        {
            dataImage = new String[0];
            dataImage = (String[])(dataSet.Tables[0].Rows[0]["logo"]);
        }
    }
    catch (Exception ex)
    {
        MessageBox.Show(""+ex);
    }
}

这是ReportViewer参数:

ReportParameter[] parameter = new ReportParameter[24];
parameter[23] = new ReportParameter("rp_logo", dataImage );
this.reportViewer1.LocalReport.SetParameters(parameter);
this.reportViewer1.RefreshReport();

但是我得到以下Exception无法将"系统字节[]"类型的对象转换为"系统字符串[]" 类型

有人可以帮我解决这个问题吗?

谢谢你的时间。

无法将类型为“System.Byte[]”的对象强制转换为类型“System.String[]”

鉴于ReportViewer需要图像的路径而不是实际的图像数据本身,最好的选择是将byte[]保存到磁盘并在参数中引用它,例如

using (var cmd = new SqlCommand("SELECT logo FROM company WHERE id = 1", spojeni))
using (var dataAdapter = new SqlDataAdapter(cmd))
using (var dataSet = new DataSet())
{
    dataAdapter.Fill(dataSet);
    if (dataSet.Tables[0].Rows.Count == 1)
    {
        // generate temp file destination
        dataImage = System.IO.Path.GetTempFileName() + ".jpg"; // use whatever extension you expect the file to be in
        File.WriteAllBytes(dataImage, (byte[])dataSet.Tables[0].Rows[0]["logo"]); // save image to disk
    }
}

字节到字符串的转换可以通过以下方式完成

 Encoding.Ascii.GetString(yourByteArray)

如果您需要进一步转换,可以执行以下操作:

Encoding.Ascii.GetString(yourByteArray).Select(c => c as string).ToArray()
相关文章: