Thursday, February 2, 2012

Add images into database

private void Form1_Load(object sender, EventArgs e)
{
try
{
DirectoryInfo Dir = new DirectoryInfo(@"\\folder");
FileInfo[] FileList = Dir.GetFiles("*.jpg", SearchOption.AllDirectories);

foreach (FileInfo FI in FileList)
{
AddFile(FI.FullName, FI.Name);
}

}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
}

private void AddFile(string fileFull, string file )
{
FileStream fs;
fs = new FileStream(fileFull, FileMode.Open, FileAccess.Read);
byte[] picbyte = new byte[fs.Length];
fs.Read(picbyte, 0, System.Convert.ToInt32(fs.Length));
fs.Close();
//open the database using odp.net and insert the data

string connstr = @"Data Source=;Initial Catalog=;User Id=;Password=;";


SqlConnection conn = new SqlConnection(connstr);
conn.Open();
SqlCommand command = new SqlCommand();
command.CommandType = CommandType.StoredProcedure;
command.Connection = conn;
command.CommandText = "procedure";

command.Parameters.Add("@Imagine", SqlDbType.Image);
command.Parameters[0].Value = picbyte;

command.Parameters.Add("@ImageName", SqlDbType.VarChar);
command.Parameters[1].Value = file;

command.Parameters.Add("@ImageValue", SqlDbType.VarChar);
command.Parameters[2].Value = file.Substring(0,1);
command.ExecuteNonQuery();
command.Dispose();
conn.Dispose();




}