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
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.
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???