0

well here is my sample code . What iam trying to do is to simply convert the file into binary format so i can insert it into the data table

            string fileName = FileUpload1.PostedFile.FileName;
            Stream strm = FileUpload1.PostedFile.InputStream;
            BinaryReader br = new BinaryReader(strm);
            Byte[] Data = br.ReadBytes((int)strm.Length);
            string fileType = FileUpload1.PostedFile.ContentType;

            SqlConnection conn = new SqlConnection(connString);
            conn.Open();
            string sql = string.Format("Insert into FileUpload (Data,fileName,fileType) values('{0}','{1}','{2}')", Data, fileName, fileType);
            Response.Write(sql);
            SqlCommand command = new SqlCommand(sql, conn);
            command.ExecuteNonQuery();
            conn.Close();
            label1.ForeColor = System.Drawing.Color.Green;
            label1.Text = "uploaded!!!!";

The problem is that everytime i execute it it says " Implicit conversion from data type varchar to varbinary(max) is not allowed. Use the CONVERT function to run this query."

Tab Alleman
  • 31,483
  • 7
  • 36
  • 52
Khan
  • 41
  • 6

1 Answers1

1

The way you try to pass Data won't work. You actually convert it to a string when you use String.Format and then you try to insert this string into a varbinary field which gives you your error.

You have to declare proper parameters for your insert query and set the type of the parameter to varbinary.

For example:

var parameter = new SqlParameter("@your_data", SqlDbType.VarBinary, -1);
command.Parameters.Add(parameter);
parameter.Value = Data;
Szymon
  • 42,577
  • 16
  • 96
  • 114
  • 1
    Thanks buddy, you are right now i am passing the data through parameter and it works – Khan Dec 31 '15 at 17:28