Tuesday, June 17, 2025

How to save a file to binary data to varbinary sql server in asp.net c#

Using fileupload field

byte[] bb = fileUpload1.FileBytes;

  SqlConnection con = new SqlConnection(ConnectionString.ConString);


            con.Open();

            SqlCommand cmd = new SqlCommand("INSERT INTO UploadFiles (FileData, ContentType) VALUES (@filedata, @ContentType)", con);

            cmd.CommandType = System.Data.CommandType.Text;

            

            

            cmd.Parameters.AddWithValue("@FileData", fileUpload1.FileBytes);

            cmd.Parameters.AddWithValue("@ContentType", fileUpload1.PostedFile.ContentType);


            cmd.ExecuteNonQuery();

            con.Close();

===============================

using binary reader

 Stream fs = fileUpload1.PostedFile.InputStream;

        BinaryReader br = new BinaryReader(fs);

        

        Byte[] bytes = br.ReadBytes((int)fs.Length);

  Stream fs = fileUpload1.PostedFile.InputStream;

 Byte[] bytes = br.ReadBytes((int)fs.Length);

No comments:

Post a Comment