Vuk Stanojevic

Vuk Stanojevic

  • 1.6k
  • 140
  • 45.6k

C# save PDF file in DB

Apr 27 2020 4:30 PM
Hi everyone,
 
i'm trying to save PDF file into SQL DB.
 
I don't get any error, but PDF is not saved in data table.
 
Here is my code:
  1. //select PDF, open/show file and show location in textbox  
  2. public void button1_Click(object sender, EventArgs e)  
  3. {  
  4. OpenFileDialog openfd = new OpenFileDialog();  
  5. openfd.Filter = "PDF Files (*.pdf)|*.pdf";  
  6. if (openfd.ShowDialog() == System.Windows.Forms.DialogResult.OK)  
  7. {  
  8. axAcroPDF1.src = openfd.FileName;  
  9. textBox1.Text = openfd.FileName;  
  10. }  
  11. else  
  12. { }  
  13. }  
  14. //save/upload button  
  15. private void button2_Click(object sender, EventArgs e)  
  16. {  
  17. if(textBox1.Text != null)  
  18. try  
  19. {  
  20. byte[] pdfb = null;  
  21. FileStream fs = new FileStream(textBox1.Text, FileMode.Open, FileAccess.Read);  
  22. BinaryReader br = new BinaryReader(fs);  
  23. pdfb = br.ReadBytes((int)fs.Length);  
  24. SqlConnection cn = new SqlConnection(@"Data Source=MAIN-PC\SQLEXPRESS;Database = " + comboBox1.Text + ";Integrated Security=True");  
  25. string query = "Insert into tblInvoices (StoreCode,Supplier,RID,Status)values ('" + comboBox2.Text + "','" + comboBox3.Text + "','" + DateTime.Now.ToString()+ "', 'Received')";  
  26. SqlCommand command = new SqlCommand(query, cn);  
  27. command.Parameters.Add("@InvoicePDF", SqlDbType.VarBinary, 8000).Value = pdfb;  
  28. cn.Open();  
  29. command.ExecuteNonQuery();  
  30. cn.Close();  
  31. MessageBox.Show("Invoice uploaded successfully", MessageBoxIcon.Information.ToString(), MessageBoxButtons.OK );  
  32. }  
  33. catch(Exception ex)  
  34. {  
  35. MessageBox.Show(ex.Message);  
  36. }  
  37. }  
SQL DB,Table config is:
 
StoreCode varchar(50) Checked
Supplier nvarchar(50) Unchecked
RID date Unchecked
CID date Checked
Status nvarchar(50) Unchecked
InvoicePDF varbinary(MAX) Checked
Managed nvarchar(50) Checked
Unchecked

Answers (2)