How to upload and download files using database in C#.NET windows application?


In this article I have explained in detail about file upload and download using database in windows application. In this example I uploaded pdf file to database and show it in data grid view if user click that file name download that pdf file from database.

Table Structure


CREATE TABLE [dbo].[PDFupload](
[ID] [int] IDENTITY(1,1) NOT NULL,
[fname] [varchar](200) NULL,
[fcontent] [image] NULL
) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]

Client side: I have design like this
Output

Server side

using System.Data;
using System.Data.SqlClient;
using System.IO;
using System.Diagnostics;

namespace FileUploadWindows
{
public partial class Form1 : Form
{
SqlConnection sqlcon = new SqlConnection(@"Data Source=.\SQlEXPRESS;AttachDbFilename=|DataDirectory|\Database1.mdf;Integrated Security=True;User Instance=True");
SqlCommand sqlcmd = new SqlCommand();
SqlDataAdapter da = new SqlDataAdapter();
DataTable dt = new DataTable();
public Form1()
{
InitializeComponent();
}

private void Form1_Load(object sender, EventArgs e)
{
LoadGrid();
}
private void button1_Click(object sender, EventArgs e)
{
OpenFileDialog fDialog = new OpenFileDialog();
fDialog.Title = "Select file to be upload";
//fDialog.Filter = "PDF Files|*.pdf|All Files|*.*";
fDialog.Filter = "PDF Files|*.pdf";
if (fDialog.ShowDialog() == DialogResult.OK)
{
textBox1.Text = fDialog.FileName.ToString();
}
}

void LoadGrid()
{
dataGridView1.Columns.Clear();
sqlcon.Open();
sqlcmd = new SqlCommand("select ID,fname from PDFupload", sqlcon);
da = new SqlDataAdapter(sqlcmd);
dt = new DataTable();
da.Fill(dt);
sqlcon.Close();
if (dt.Rows.Count>0)
{
DataGridViewLinkColumn links = new DataGridViewLinkColumn();
links.UseColumnTextForLinkValue = true;
links.HeaderText = "Download";
links.DataPropertyName = "lnkColumn";
links.ActiveLinkColor = Color.White;
links.LinkBehavior = LinkBehavior.SystemDefault;
links.LinkColor = Color.Blue;
links.Text = "Click here";
links.TrackVisitedState = true;
links.VisitedLinkColor = Color.YellowGreen;
dataGridView1.Columns.Add(links);
dataGridView1.DataSource = dt;

dataGridView1.AutoResizeColumns();
}
}

private void button2_Click(object sender, EventArgs e)
{
string filetype;
string filename;

filename=textBox1.Text.Substring(Convert.ToInt32(textBox1.Text.LastIndexOf("\\"))+1,textBox1.Text.Length - (Convert.ToInt32(textBox1.Text.LastIndexOf("\\"))+1));
filetype=textBox1.Text.Substring(Convert.ToInt32(textBox1.Text.LastIndexOf("."))+1,textBox1.Text.Length - (Convert.ToInt32(textBox1.Text.LastIndexOf("."))+1));

//Validate user upload only specific bytes - un comment below lines if you need to validate only PDF files

if (filetype.ToUpper() != "PDF")
{
MessageBox.Show("Upload Only PDF Files");
return;
}

byte[] FileBytes = null;

try
{
// Open file to read using file path
FileStream FS = new FileStream(textBox1.Text, System.IO.FileMode.Open, System.IO.FileAccess.Read);

// Add filestream to binary reader
BinaryReader BR= new BinaryReader(FS);

// get total byte length of the file
long allbytes = new FileInfo(textBox1.Text).Length;

// read entire file into buffer
FileBytes = BR.ReadBytes((Int32)allbytes);

// close all instances
FS.Close();
FS.Dispose();
BR.Close();
}
catch (Exception ex)
{
MessageBox.Show("Error during File Read " + ex.ToString());
}

//Store File Bytes in database image filed

sqlcon.Open();
SqlCommand sqlcmd = new SqlCommand("insert into PDFupload(fname,fcontent) values (@FN, @FB)", sqlcon);
sqlcmd.Parameters.AddWithValue("@FN", filename);
sqlcmd.Parameters.AddWithValue("@FB", FileBytes);
sqlcmd.ExecuteNonQuery();
sqlcon.Close();
LoadGrid();
}

private void dataGridView1_CellContentDoubleClick(object sender, DataGridViewCellEventArgs e)
{

}

//Below code is used to open Your stored PDF
private void dataGridView1_CellContentClick(object sender, DataGridViewCellEventArgs e)
{
if (e.ColumnIndex == 0)
{
string id;
FileStream FS = null;
byte[] dbbyte;

//Get selected file ID field
id = dataGridView1.Rows[e.RowIndex].Cells[1].Value.ToString();

sqlcon.Open();
sqlcmd = new SqlCommand("select * from PDFupload where ID='" + id + "'", sqlcon);
da = new SqlDataAdapter(sqlcmd);
dt = new DataTable();
da.Fill(dt);
sqlcon.Close();


if (dt.Rows.Count > 0)
{
//Get a stored PDF bytes
dbbyte = (byte[])dt.Rows[0]["fcontent"];

//store file Temporarily
string filepath = "D:\\temp.pdf";


//Assign File path create file
FS = new FileStream(filepath, System.IO.FileMode.Create);

//Write bytes to create file
FS.Write(dbbyte, 0, dbbyte.Length);

//Close FileStream instance
FS.Close();


// Open fila after write

//Create instance for process class
Process Proc = new Process();

//assign file path for process
Proc.StartInfo.FileName = filepath;
Proc.Start();
}
sqlcon.Close();
}
}
}
}

Ouput
If I click Download column click here link download that file from database and open automatically in PDF format .

Source Code Detail:
Here with I have attached source code of windows application code download it and try to upload and download PDF in database.
Front End : Windows form design
Code Behind : C#

Conclusion:
I hope this article help to know file stored in database.


Attachments

  • Source code (43580-24917-FileUploadWindows.rar)
  • Comments

    Guest Author: Anirban dutta28 Jun 2012

    i want to download any types files which already in sql table,and need to save as per my choose location in ADO.net c# will anyone help me???

    Author: Ravindran20 Jul 2012 Member Level: Gold   Points : 1

    Anirban,

    Use the above code snippet for any file store add one additional field in the table to store file type, based on that create temp file in this line

    //store file Temporarily
    string filepath = "D:\\temp.xls"; //anything what you want that file format

    Guest Author: Higor22 Nov 2012

    Great article, helped a lot. Thanks.

    Guest Author: Senthil25 Nov 2012

    Hi can you tell me the table structure of "PDFupload" table that you have used here

    Guest Author: senthil Gopi25 Nov 2012

    HI I'm Using IBM DB2 database for Insert operation, here there is no specific data type as Image in DB2, Kindly help me, how can I insert a file in DB2 database

    Author: Ravindran25 Nov 2012 Member Level: Gold   Points : 0

    Sethil,

    Please see above first i defined table and then start article just copy that query and run to create table in your sql server.

    Guest Author: Senthil25 Nov 2012

    HI Ravindran,

    Yes I got the table structure, but the problem here is I'm using IBM DB2 database, in that DB there is no datatype called Image,instead it uses BLOB data type for storing the files, I need your kind help to using DB2 database

    Guest Author: m{}b@yu29 Nov 2012

    Hi thnx u saved me. but it gives me error at run time when grid view load: it says

    The following exception occurred in the datagridview:
    system.ArgumentException:Parameter is not valid.............................

    Guest Author: srinivas21 Feb 2013

    thanks buddy

    Guest Author: vinayakmoorthy04 Apr 2013

    Thank to upload this source code sir but still it has error while am clicking download link (A required privilege is not held by the client.)

    Guest Author: vinayakmoorthy04 Apr 2013

    this code has some error.. please help me .. ther error accuring while am clicking download link in grideview.. error is
    (A required privilege is not held by the client.)

    Guest Author: Faiz09 May 2013

    Hello! Please it flag some errors when I use the code as written above. The error is (The parametrized query '(@FN nvarchar(15),@FB nvarchar(4000))insert into PDFupload (fnam'expects the parameter '@FB',which was not supplied.....pls kindly help me out.

    Guest Author: kirti28 May 2013

    How to retrieve a file from database.(C# windows application)? I have saved my file(.doc,.txt) in database(sql server 2008) and now I want to retrieve that saved file.File should be open either directly or in rich text box or in other control.



  • Do not include your name, "with regards" etc in the comment. Write detailed comment, relevant to the topic.
  • No HTML formatting and links to other web sites are allowed.
  • This is a strictly moderated site. Absolutely no spam allowed.
  • Name:
    Email: