如何在数据集中发送字节数组并从中读取

时间:2014-06-10 06:31:32

标签: c# asp.net dataset bytearray

我想在数据集中发送字节,并且我有一列数据类型varbinary(MAX)。当我尝试发送一个字节数组,而不是在数据集中显示一个字节数组时,它显示以下数据。我不知道它是纯字节数组还是显示字节数。我认为“ProjectIcons”列应返回的值是 {bytes [1305]} ....

1)如果是字节,那么我如何从数据集中读取字节。enter image description here

请告诉我错误的地方。我使用下面的代码:

public DataSet GetAllProjectStandardIcons2()
    {
        var images = (from p in dbModel.tbl_STANDARDPROJECTICONS select new ProjectDetails1 
        {   
            id = p.id,
            ProjectIcons = (Byte[])(p.ProjectIcons)
        }).ToList();

        DataTable dt = new DataTable();
        if (images.Count > 0)
            {
                Byte[] ProjectIcons;
                DataColumn dc = new DataColumn("id");
                DataColumn dc1 = new DataColumn("ProjectIcons");
                dt.Columns.Add(dc);
                dt.Columns.Add(dc1);
                for (var i = 0; i < images.Count(); i++)
            {

                DataRow row = dt.NewRow();
                row["id"] = images[i].id;
                ProjectIcons = (Byte[])images[i].ProjectIcons;
                row["ProjectIcons"] = ProjectIcons;
                dt.Rows.Add(row);
            }
        }
        DataSet ds = new DataSet();
        ds.Tables.Add(dt);
        return ds;
    }

2 个答案:

答案 0 :(得分:2)

我找到了解决方案需要将bytearray转换为base64数组,以下代码对我有用

public DataSet GetAllProjectStandardIcons2()
        {
            var images = (from p in dbModel.tbl_STANDARDPROJECTICONS
                          select new ProjectDetails1
                          {
                              id = p.id,
                              ProjectIcons = (Byte[])(p.ProjectIcons)

                          }).ToList();


            DataTable dt = new DataTable();
            if (images.Count > 0)
            {
                Byte[] ProjectIcons;
                DataColumn dc = new DataColumn("id");
                DataColumn dc1 = new DataColumn("ProjectIcons");
                dt.Columns.Add(dc);
                dt.Columns.Add(dc1);
                for (var i = 0; i < images.Count(); i++)
                {

                    DataRow row = dt.NewRow();
                    row["id"] = images[i].id;
                    row["ProjectIcons"] = Convert.ToBase64String(images[i].ProjectIcons);//convert here byte array to base64
                    dt.Rows.Add(row);
                }
            }
            DataSet ds = new DataSet();
            ds.Tables.Add(dt);
            return ds;

        }

答案 1 :(得分:2)

请尝试以Base64格式保存图像并以相同格式检索,然后尝试以字节转换...尝试以下代码

for (var i = 0; i < images.Count(); i++)
                {

                    DataRow row = dt.NewRow();
                    row["id"] = images[i].id;
                    row["ProjectIcons"] = Convert.ToBase64String(images[i].ProjectIcons);//convert here byte array to base64
                    dt.Rows.Add(row);
                }