How to read files from directory and insert into database as bytes?
In this article I am going to explain about read all files from directory and insert into database table as a byte format.
Description
In this project I have convert all files as bytes and insert in to sql server table. This technique is useful for you in your project work.
Create table like below
create table fupload(ImgName varchar(250),Img image)Cde Behind
Here i read all files from the folder / filter files based on the condition and insert into database.
using System.Data;
using System.Data.SqlClient;
public partial class _Default : System.Web.UI.Page
{
SqlConnection sqlcon = new SqlConnection(ConfigurationManager.ConnectionStrings["Con"].ConnectionString);
SqlCommand sqlcmd = new SqlCommand();
protected void Page_Load(object sender, EventArgs e)
{
}
protected void Button1_Click(object sender, EventArgs e)
{
try
{
sqlcon.Open();
byte[] cnt = null;
//Source directory to read files
DirectoryInfo di = new DirectoryInfo("D:\\DNS\\samp");
//if you want only jpg files then filter it
FileInfo[] ArrFi = di.GetFiles("*.jpg");
foreach (FileInfo fi in ArrFi)
{
cnt = FileToByteArray(fi.FullName);
SqlCommand sqlcmd = new SqlCommand("insert into fupload(ImgName,Img) values (@Im, @Img)", sqlcon);
sqlcmd.Parameters.Add("@Im", fi.Name);
sqlcmd.Parameters.Add("@Img", cnt);
sqlcmd.ExecuteNonQuery();
}
}
catch (Exception ex)
{
}
finally
{
sqlcon.Close();
}
}
public byte[] FileToByteArray(string fname)
{
byte[] cnt = null;
try
{
System.IO.FileStream fs = new System.IO.FileStream(fname, System.IO.FileMode.Open, System.IO.FileAccess.Read);
System.IO.BinaryReader br = new System.IO.BinaryReader(fs);
long tb = new System.IO.FileInfo(fname).Length;
cnt = br.ReadBytes((Int32)tb);
fs.Close();
fs.Dispose();
br.Close();
}
catch (Exception ex)
{
}
return cnt;
}
}Source code:
Client Side: ASP.NET
Code Behind: C#Conclusion
I hope this article is help you to know about read files from folder and insert into database table as bytes.