Search code examples
c#sql-servert-sqlado.net

How convert a Byte[] to a data to insert a value in a varbinary(max) column in SQL Server?


I have a object with a byte[] property, and I would like to convert this value to the correct value to can insert it into the database using T-SQL.

But I don't know how I could convert the byte[] to the correct value for T-SQL for the insert.

Thanks.


Solution

  • Create a Console Application project and try this code

    // Sample Class
    public class MyClass
    {
        public byte[] data;
    }
    
    // Main 
    static void Main(string[] args)
    {
        MyClass cls = new MyClass();
        using (SqlConnection cn = new SqlConnection("CONNECTION STRING"))
        {
            cn.Open();
            using (SqlCommand cmd = new SqlCommand("insert into MyTable values (@data)", cn))
            {
                cmd.Parameters.AddWithValue("@data", cls.data);
                cmd.ExecuteNonQuery();
            }
        }
    }