Storing PDF file into database and reading the same from DB

May 17 2014 6:56 AM
Hello friends,

I am using Form View control.  Here, I have show coding for your kind attention. Because,  I am trying store PDF file into MS-SQL SERVER 2008 and reading the same for viewing.  But, while trying to read the file, it is giving error as "file may be corrupted....".

Below coding for uploading PDF file to Database:

                    Com.strTmpcode = Path.GetFileName(((FileUpload)row.FindControl("Fupd")).PostedFile.FileName);
                    
                    ((FileUpload)row.FindControl("Fupd")).SaveAs(Server.MapPath(Com.strTmpcode));

                    string filePath = Server.MapPath(Com.strTmpcode);

                    FileStream fStream = File.OpenRead(filePath);
                    PropLayer.compdimdrwg = new byte[fStream.Length];
                    fStream.Read(PropLayer.compdimdrwg, 0, (int)fStream.Length);
                    fStream.Close();

Below coding for viewing from database:
(Form view controls command event)

            if (e.CommandName.Equals("OpenPDF"))
            {
                string sPathToSaveFileTo = @"C:\SelectedFile.pdf";

                Com.strSQL = "select compdimdrwg from mstcompdimhdr where compdimcode = '" + ((Label)row.FindControl("compdimcodeLabel")).Text.Trim() + "'";
                Com.objDRdr = Conn.ReturnDataReader(Com.strSQL);
                if (Com.objDRdr.Read())
                {
                    if (!Com.objDRdr.IsDBNull(0))
                    {
                            byte[] fileData = (byte[])Com.objDRdr.GetSqlBinary(0);
                            FileStream fs = new FileStream(sPathToSaveFileTo, FileMode.Create, FileAccess.ReadWrite);
                            BinaryWriter bw = new BinaryWriter(fs);
                            bw.Write(fileData);
                            bw.Close();
                    }
                    else
                    {
                        ScriptManager.RegisterStartupScript(this, GetType(), "DuroIPMS", "alert('No drawing file avilable!!!')", true);
                    }
                }
                Com.objDRdr.Dispose();
            }

Please, help me to know what is wrong.

Thanking you,

Yours sincerely,
Saravanan.S

Answers (1)