ASP.NET - implicit conversion from data type varchar to varbinary(max) is not allowed

Asked By shailendra verma on 29-Nov-18 01:41 AM
string filename = Path.GetFileName(FileUpload1.PostedFile.FileName);
        string contentType = FileUpload1.PostedFile.ContentType;
        using (Stream fs = FileUpload1.PostedFile.InputStream)
        {
            using (BinaryReader br = new BinaryReader(fs))
            {
                byte[] bytes = br.ReadBytes((Int32)fs.Length);
                string constr = ConfigurationManager.ConnectionStrings["constr"].ConnectionString;
                using (SqlConnection con = new SqlConnection(constr))
                {
                    con.Open();
                    string query = "UPDATE tblFiles SET Name='" + filename.ToString() + "',ContentType='" + contentType.ToString() + "',Data='" + ((object)bytes) + "' WHERE id = '" + 1 + "'"; // error getting
                    using (SqlCommand cmd = new SqlCommand(query))
                    {
                        cmd.Connection = con;
                                            
                        cmd.ExecuteNonQuery();
                        con.Close();
                    }
                }
            }
        }
        Response.Redirect(Request.Url.AbsoluteUri);
Robbe Morris replied to shailendra verma on 01-Dec-18 11:03 AM
You'll need to use a SqlParameter added to your SqlCommand .Parameters collection.  Then adjust your sql to look like this:

  update mytable
    set myvarbinarycolumn = @myvarbinarycolumvariablename
  where mykey = @mykey


 Use the "@" oriented variables above as the parameter names for your two SqlParameter objects you create and add to the SqlCommand .Parameters collection.