Title: Upload file to database with C#
Language: C# 3.5
Tools: Visual C# 2008 Express Edition
Database: SQL Server 2005 Express Edition
FileName: FileDatabase.zip
Table
.jpg)
Source Code
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Data.SqlClient;
using System.Configuration;
using System.IO;
namespace WindowsFormsApplication1
{
public partial class MainForm : Form
{
private string connectionString;
private SqlDataAdapter da;
private DataSet ds;
public MainForm()
{
InitializeComponent();
connectionString = ConfigurationManager.ConnectionStrings["FileDB"].ConnectionString;
string selectCommandText = "select * from FileTable";
da = new SqlDataAdapter(selectCommandText, connectionString);
SqlCommandBuilder cb = new SqlCommandBuilder(da);
da.InsertCommand = cb.GetInsertCommand();
da.UpdateCommand = cb.GetUpdateCommand();
da.DeleteCommand = cb.GetDeleteCommand();
ds = new DataSet();
da.Fill(ds, "FileTable");
fileComboBox.DataBindings.Add("Text", ds.Tables["FileTable"], "FileName");
}
private void uploadButton_Click(object sender, EventArgs e)
{
DialogResult result = openFileDialog1.ShowDialog();
if (result == DialogResult.OK)
{
DataRow row = ds.Tables["FileTable"].NewRow();
FileStream fs = new FileStream(openFileDialog1.FileName, FileMode.Open);
BinaryReader br = new BinaryReader(fs);
byte[] bytes = br.ReadBytes((int)fs.Length);
int lastIndex = openFileDialog1.FileName.LastIndexOf(@"\");
row["FileName"] = openFileDialog1.FileName.Substring(lastIndex + 1);
row["FileBinary"] = bytes;
ds.Tables["FileTable"].Rows.Add(row);
da.Update(ds.Tables["FileTable"]);
}
}
private void downLoadButton_Click(object sender, EventArgs e)
{
DataRow[] rows = ds.Tables["FileTable"].Select("FileName='" + fileComboBox.Text + "'");
if (rows.Length > 0)
{
saveFileDialog1.FileName = rows[0]["FileName"].ToString();
DialogResult result = saveFileDialog1.ShowDialog();
if (result == DialogResult.OK)
{
byte[] bytes = (byte[])rows[0]["FileBinary"];
FileStream fs = new FileStream(saveFileDialog1.FileName, FileMode.OpenOrCreate, FileAccess.Write);
BinaryWriter bw = new BinaryWriter(fs);
bw.Write(bytes);
fs.Close();
}
}
}
}
}
File Attachment(s):
FileDatabase.zip (285kb) downloaded 165 time(s).
Imagination is more Important than Knowledge... /A.Einstein