views:

432

answers:

2

I have sql data type image to store the state of the webparts but in .Net it is Byte[]. How do I convert Byte[] to sql image for insert and other operations.

+10  A: 

Just specify Binary as the parameter type, it's value can be a byte[]

byte[] data; // wherever this comes from

using (SqlCommand command = new SqlCommand())
{
    command.Connection = connection;
    command.CommandText = "INSERT INTO BinaryTable (BinaryData) VALUES (@BinaryData)";

    SqlParameter param = new SqlParameter("@BinaryData", SqlDbType.Binary);
    param.Value = data;

    command.Parameters.Add(param);
    command.ExecuteNonQuery();
}

Edit: Also worth noting is that if you are using SQL Server 2005/2008, then you should use VARBINARY(MAX) instead of IMAGE since the latter is deprecrated.

Richard Szalay
A: 

Here is a sample function

public bool AddCompanyIcon(string MakeName, byte[] BytesOriginal,string ImageName)
    {
        try
        {
            System.Data.SqlClient.SqlParameter[] ImgPara = new SqlParameter[3];
            ImgPara[0] = new SqlParameter("@MakeName", MakeName);
            ImgPara[1] = new SqlParameter("@MakeIcon", BytesOriginal);
            ImgPara[2] = new SqlParameter("@ImageName", ImageName);

            db.ExecuteScalerSP("sp_AddAutoCompanyLogo", ImgPara);
            db.CloseConnection();
            return true;
        }
        catch 
        {
            return false;
        }
    }

Below is sp_AddAutoCompanyLogo stored procedure

ALTER PROCEDURE [dbo].[sp_AddAutoCompanyLogo] 
    -- Add the parameters for the stored procedure here
    @MakeName varchar(50),
    @MakeIcon image,
    @ImageName varchar(50)
AS
BEGIN
    -- SET NOCOUNT ON added to prevent extra result sets from
    -- interfering with SELECT statements.
    SET NOCOUNT ON;
    -- Insert statements for procedure here
    insert into IVAutoGalleryLogos(MakeName,MakeIcon,ImageName) 
    values(upper(@MakeName),@MakeIcon,@ImageName)
END

Hope this will help...

IrfanRaza