Friday, August 30, 2013

How to Save PDF/Image/documents in Database using C#

Save File/Images on database. For this we need to create a table with column type varbinary(Max).
Create table test (ID int identity(100,1), filename varbinary(max) )
In C# declare one variable as a binary and read the file by inputstream. ------- save file in db
if (Fileupload1.UploadedFiles.Count > 0) { string fileName = Path.GetFileName(file1.FileName); string fileExtension = Path.GetExtension(file1.FileName); string documentType = string.Empty; switch (fileExtension) { case ".pdf": documentType = "application/pdf"; break; case ".xls": documentType = "application/vnd.ms-excel"; break; case ".xlsx": documentType = "application/vnd.ms-excel"; break; case ".doc": documentType = "application/vnd.ms-word"; break; case ".docx": documentType = "application/vnd.ms-word"; break; case ".gif": documentType = "image/gif"; break; case ".png": documentType = "image/png"; break; case ".jpg": documentType = "image/jpg"; break; }
-- Calculate size of file to be uploaded
int fileSize = file1.ContentLength; --Create array and read the file into it byte[] documentBinary = new byte[fileSize]; file1.InputStream.Read(documentBinary, 0, fileSize); -- pass that value to database // SQL command String command = "INSERT INTO test (filename) " + "VALUES( +documentBinary+ );"; // Create the command object ADOCommand cmdAdder = new ADOCommand(command,DB_CONN_STRING); cmdAdder.ActiveConnection.Open(); // Execute the SQL command int a = cmdAdder.ExecuteNonQuery(); ---end ------Retrieve file ADOConnection conn = new ADOConnection(DB_CONN_STRING); conn.Open(); ADODataReader dr; ADOCommand cmd = new ADOCommand( "SELECT * FROM test", conn ); cmd.Execute( DataTableReader); while (dReader.Read() || (!Convert.IsDBNull(dReader["filename"]))) { try{ string fileName = string.Empty; fileName = gdCheckList.DataKeys[e.Row.RowIndex].Value.ToString().Trim(); byte[] documentBinary = (byte[])dReader["filename"]; FileStream fStream = new FileStream(Server.MapPath(strvar + fileName), FileMode.Create); fStream.Write(documentBinary, 0, documentBinary.Length); fStream.Close(); fStream.Dispose(); hyfile.Enabled = true; HyperLinlk1.NavigateUrl = strvar + fileName; }
I hope this will help us.