-1

Code query database:

I can't save the PDF files to my database, I have a serious problem in the database storage area.

public void ADDWORK(String MAW, string NAMEW, string IDUSER, bool Image,string room, byte[] document,string content,bool donework)
{
    String strSql = string.Format("INSERT INTO WORK(IDWORD,NAMEWORk,IDUSER,IMAGES,IDROOM,DOCUMENTS,CONTENT,DONEWORK)VALUES('{0}',N'{1}',N'{2}','{3}',N'{4}',N'{5}',N'{6}',N'{7}')"
        , MAW, NAMEW, IDUSER, Image,room,document,content,donework);
    db.ExecuteNonQuery(strSql);
}

Code call function:

byte[] pdf;
public void UploadFlie(string file)
{
    FileStream fileStream = File.OpenRead(file);
    byte[] contents = new byte[fileStream.Length];
    fileStream.Read(contents, 0, (int)fileStream.Length);
    fileStream.Close();
    pdf = contents;
}

private void button1_Click(object sender, EventArgs e)
{
    UploadFlie(filename);
     dg.ADDWORK(idword, textBox1.Text,"1",  false,"ROOM1", pdf, richTextBox1.Text, false);
    MessageBox.Show("Done!");
}
kaylum
  • 13,833
  • 2
  • 22
  • 31
Nhi
  • 15
  • 4
  • Can you better describe what you mean by _I can't save the pdf file to my database, I have a serious problem in the database storage area_ – Flydog57 Jan 27 '22 at 19:51
  • Can you elaborate on how your code "doesn't work"? What were you expecting, and what actually happened? If you got an exception/error, post the line it occurred on and the exception/error details which can be done with a [mre]. Please [edit] your question to add these details into it or we may not be able to help. – gunr2171 Jan 27 '22 at 19:52
  • 3
    I'm compelled to point out that you have a SQL injection vulnerability. You're formatting arbitrary strings into SQL string expressions, `'{0}'`, etc. Use parameters. Please. – madreflection Jan 27 '22 at 19:59
  • 2
    Why do you want to fill very expensive SQL Server storage space (and memory) with files? This is what a file system is efficient (and cost effective) at doing. Using a database's resources to fill it up with PDF files seems... anti-profit. – Aaron Bertrand Jan 27 '22 at 20:10
  • 1
    A further note on parameterizing your query... You have a `byte[] document` parameter that will be formatted into the query as `'System.Byte[]'`, which is not a valid varbinary expression, and definitely *not* what you want in the column anyway. Parameters will guard you from errors like this. – madreflection Jan 27 '22 at 20:13
  • 1
    The following may be helpful: https://stackoverflow.com/questions/66612039/why-is-my-image-from-database-not-displaying-properly-in-my-picturebox/66616751#66616751 . If using `SqlDbType.VarBinary`, set size to `-1`. You may consider storing the filenames in the database and saving the actual files on a file system. – Tu deschizi eu inchid Jan 28 '22 at 00:38
  • 2
    `db.ExecuteNonQuery(strSql);` suggests that you're sharing a single `SqlCommand` object between methods. Don't do that, you should be creating `SqlConnection` and `SqlCommand` objects as and when you need them and disposing of them as soon as you're done using them. (`using` constructs will take care of automatic disposal.) That will also make it much easier for you to use Parameterized Queries with [SqlParameter](https://learn.microsoft.com/en-us/dotnet/api/system.data.sqlclient.sqlparameter) instead of trying to inject values into queries like you're currently attempting to do. – AlwaysLearning Jan 28 '22 at 03:19
  • Does this answer your question? [Why do we always prefer using parameters in SQL statements?](https://stackoverflow.com/questions/7505808/why-do-we-always-prefer-using-parameters-in-sql-statements) – Charlieface Jan 28 '22 at 03:31

1 Answers1

0

here is my example how to get any file and save it on database.

I use two diffrent methods

  1. Saving byte array.
  2. Saving Stream

First you need to create column varbinary(MAX) in my case I called it - PdfFile and PdfExtn column to save the type of the file As varchar(10) (You can use 4).

  1. Saving byte array:

         private void btnGetFile_Click(object sender, EventArgs e)
     {
         OpenFileDialog openFileDialog1 = new OpenFileDialog();
         DialogResult result = openFileDialog1.ShowDialog(); // Show the dialog.
         if (result == DialogResult.OK) // Test result.
         {
             string file = openFileDialog1.FileName;
             string extn = new FileInfo(file).Extension;
    
             try
             {
                 byte[] fileBytes = File.ReadAllBytes(file);
                 string cmd = "INSERT INTO Employee(Id,FirstName,LastName,Email,Password,PdfFile,FileExtn) VALUES (@Id,@FirstName,@LastName,@Email,@Password,@PdfFile,@FileExtn)";
    
                 List<SqlParameter> l = new List<SqlParameter>();
                 l.Add(new SqlParameter("@Id", "101"));
                 l.Add(new SqlParameter("@FirstName", "Aviv"));
                 l.Add(new SqlParameter("@LastName", "Halevy"));
                 l.Add(new SqlParameter("@Email", "Assadsa@gmail.com"));
                 l.Add(new SqlParameter("@Password", "123456"));
                 SqlParameter sp = new SqlParameter("@PdfFile", SqlDbType.VarBinary, -1);
                 sp.Value = fileBytes;
                 l.Add(sp);
                 l.Add(new SqlParameter("@FileExtn", extn));
                 if (DAL.Database.ParametersCommand(cmd, l) > 0)
                     textBox1.Text = "SUCCESS! Save with byte array";
             }
             catch (IOException ex)
             {
    
             }
         }
     }
    

Write the file from bytes:

  private void btnReadFromDb_Click(object sender, EventArgs e)
    {
        string cmd = "SELECT * FROM Employee WHERE Id = '101'";
        string path = "YOUR_PATH\\Test";
        DataTable dt = DAL.Database.GetDataTable(cmd);
        if (dt != null && dt.Rows.Count > 0)
        {
            Byte[] file = (Byte[])dt.Rows[0]["PdfFile"];
            string extn = dt.Rows[0]["FileExtn"].ToString();
            path = Path.Combine(path, "Test321"+extn);

            File.WriteAllBytes(path, file);
            Process.Start(path);
        }
    }

And the result:

enter image description here

  1. Using Stream

    private void button1_Click(object sender, EventArgs e)
     {
    
         OpenFileDialog openFileDialog1 = new OpenFileDialog();
         DialogResult result = openFileDialog1.ShowDialog(); // Show the dialog.          
         if (result == DialogResult.OK) // Test result.
         {
             string file = openFileDialog1.FileName;
             using (Stream stream = File.OpenRead(file))
             {
                 byte[] buffer = new byte[stream.Length];
                 stream.Read(buffer, 0, buffer.Length);
                 string extn = new FileInfo(file).Extension;
                 string cmd = "INSERT INTO Employee(Id,FirstName,LastName,Email,Password,PdfFile,FileExtn) VALUES (@Id,@FirstName,@LastName,@Email,@Password,@PdfFile,@FileExtn)";
    
                 List<SqlParameter> l = new List<SqlParameter>();
    
                 l.Add(new SqlParameter("@Id", "102"));
                 l.Add(new SqlParameter("@FirstName", "Aviv"));
                 l.Add(new SqlParameter("@LastName", "Halevy"));
                 l.Add(new SqlParameter("@Email", "Assadsa@gmail.com"));
                 l.Add(new SqlParameter("@Password", "123456"));
                 l.Add(new SqlParameter("@PdfFile", buffer));
                 l.Add(new SqlParameter("@FileExtn", extn));
                 if (DAL.Database.ParametersCommand(cmd, l) > 0)
                     textBox1.Text = "SUCCESS! Save with Stream";
             }
         }
     }
    

Write the file from stream:

   private void button2_Click(object sender, EventArgs e)
    {
        string cmd = "SELECT * FROM Employee WHERE ID = '102'";
        string path = "YOUR_PATH\\Test";
        DataTable dt = DAL.Database.GetDataTable(cmd);
        if (dt != null && dt.Rows.Count > 0)
        {
            Byte[] file = (Byte[])dt.Rows[0]["PdfFile"];
            string extn = dt.Rows[0]["FileExtn"].ToString();
            path = Path.Combine(path, "Test123"+extn);

            File.WriteAllBytes(path, file);
            Process.Start(path);
        }
    }

And the result:

enter image description here

Note: In my examples the DAL project has a static methods that runs my sql commands.

Aviv Halevy
  • 161
  • 1
  • 10
  • I have just try this with large pdf file with byte array that contain `{byte[4903685]}` and got the same result with both methods. Can you give me any referance to the limit your are talking about. – Aviv Halevy Jan 28 '22 at 15:39
  • tnx u @user9938 , didnt know that. I have fixed my answer now. – Aviv Halevy Jan 28 '22 at 16:02