1

I have a C# application that is uploading files to a sql server, I use this code to get the pdf file and then I change it to "bytes" for upload on the SQL Server database.

private void mButtonAddCV_Click(object sender, EventArgs e)
{
    openFileDialog1.Filter = "PDF Files | *.pdf";
    if (openFileDialog1.ShowDialog() == System.Windows.Forms.DialogResult.OK)
    {
        if (openFileDialog1.FileName.Length > 0)
        {
            pathCV = openFileDialog1.FileName;
        }
    }

    // Read the file and convert it to Byte Array
    string filePath = pathCV;
    string contenttype = String.Empty;

    contenttype = "application/pdf";

    if (contenttype != String.Empty)
    {
        Stream fs = File.OpenRead(filePath);
        BinaryReader br = new BinaryReader(fs);
        bytes = br.ReadBytes((Int32)fs.Length);
    }
}

I use the code below to upload the file:

if (!mConnector.Update("INSERT INTO **** (***, ***, CV) " +
                            "VALUES ('" + *** + "', '" + *** + "', '" + bytes + "')"))
{
    Messages.errorMessageBox("This CV already exists.");
}
else
{
    ChangeScreen(ActiveScreen, ActiveScreens.ActiveScreen_CVList);
}

But now I don't know how to download this file and how to make a pdf file with the data stored on the database to see it. Can anyone help me?

Thanks!

Imrik
  • 674
  • 2
  • 14
  • 32
  • I doubt you are able to insert your bytes? bytes in SQL Server is a long hex value like 0x9034BA94F832C.... – Manish Dalal Aug 25 '14 at 11:28
  • 1
    There must be a compile time error when you try to concatenate a string and byte array.... (or, on another thought, it is inserting System.Byte[] into the CV column) – Manish Dalal Aug 25 '14 at 11:29
  • I insert this, I don't know if this is a my pdf.file or what: bytes[760483]: [0] 37, [1] 80, [2] 114, ... , [760483] 34 – Imrik Aug 25 '14 at 11:31
  • as far as i know... a pdf file starts with %PDF followed by a version number which means [0]37, [1]80, [2]68, [3]70... – Manish Dalal Aug 25 '14 at 11:35
  • yes, is that my "bytes", i put the other numbers as random numbers, but my "bytes" have this values that you said – Imrik Aug 25 '14 at 11:38
  • how can I translate them to a pdf file? – Imrik Aug 25 '14 at 11:38
  • it depends on the type of application you are developing, for web applications, you can change the mime type and write the bytes in response stream and your browser will handle the file. in windows forms application, you can save these bytes as a temporary file and start the file (windows file mapping will launch the respective application).... or.... many more ways...:P – Manish Dalal Aug 25 '14 at 13:02

3 Answers3

2

First off, let's change the way you are forming your insert statement so you aren't opening up your system to sql injection. This will also make the insert statement easier to work with

var command = new SqlCommand("INSERT INTO myTable (x, y, z) VALUES (@a, @b, @c)", sqlConnection);
command.Parameters.Add(new SqlParameter("@a", bytes));
command.Parameters.Add(new SqlParameter("@b", bValue));
command.Parameters.Add(new SqlParameter("@c", bValue));

var resultingRows = command.ExecuteNonQuery();

To read the data out, use ExecuteReader, then the File object to save it to the disk.

var command = new SqlCommand("Select a from myTable", sqlConnection);
var reader = command.ExecuteReader();
reader.Read();
var pdfBinaryBuffer = (byte[])reader[0];

// Save file to disk
var file = File.Create("myFile.pdf", pdfBinaryBuffer.Length);
file.Write(pdfBinaryBuffer, 0, pdfBinaryBuffer.Length);
file.Close();
Dave
  • 897
  • 8
  • 8
  • I recieve the results on this sentence: List lResults = mConnector.Query("SELECT CV FROM *** WHERE DNI='" + valueToSearch + "'", lCols); Can I do all you do with that? I have my own class to connect and make operations to my database and I prefer to continue with that if it's possible. Thanks! :) – Imrik Aug 25 '14 at 11:56
  • The best way to do it would be to use an orm, like EF6. This will solve your sql injection problems and allow you to get all rows at once. It will take a bit to setup, but in the end, it will save you a ton of time. I wouldn't roll your own. – Dave Aug 25 '14 at 12:07
0

I suggest you to insert your byte data using SqlParameters... see Inserting a byte array into sql server

Then, read the record using SqlDataReader's GetBytes(...) function see here.

Community
  • 1
  • 1
Manish Dalal
  • 1,768
  • 1
  • 10
  • 14
0

I suggest you to upload pdf and save it in separate folder. you can save the path in database table that I think it is good.

Here is code for file upload

Drag “Fileupload” control to .aspx page (Use this code is for save .PDF to folder)

protected void fileUpload()
{
 if (fileUp.HasFile)
            {

                fileUp.SaveAs(Server.MapPath("~/PoPDF/" + this.txtCusPo.Text +".PDF"));
                string imgPrintPo = this.txtCusPo.Text + ".PDF";

            }
}

Here is code for file download

You can put this code in button event but here I have used GridView row command event.

protected void gridview_RowCommand(object sender, GridViewCommandEventArgs e)
{
   GridViewRow row = (GridViewRow)(((LinkButton)e.CommandSource).NamingContainer);
   if (e.CommandName == "SelectDownload")
   {

      Response.Clear();
      Response.ContentType = "application/octet-stream";
      Response.AppendHeader("Content-Disposition", "filename=" + e.CommandArgument);
      Response.TransmitFile(Server.MapPath("~/PoPDF/") + e.CommandArgument);
        //Response.Flush();
             Response.End();
   }

}
tharinda
  • 9
  • 7