Save Images in SQL Server using C#

This C# program explain how you can store images into SQL Server Database. First you need to Create New Project and give the Name of the project is SaveImage Add the label, TextBox, command button and picture box control and copy this code and paste. So please change the data source name, database name and Table name.
Please Give the Comments.
usingSystem;
usingSystem.Collections.Generic;
usingSystem.ComponentModel;
usingSystem.Data;
usingSystem.Drawing;
usingSystem.Linq;
usingSystem.Text;
usingSystem.Windows.Forms;
usingSystem.Data.SqlClient;
usingSystem.Configuration;
usingSystem.IO;
namespaceSaveImage
{
    public partial class Form1 : Form
    {
        publicForm1()
        {
            InitializeComponent();
        }
        privatevoid CmdBrowse_Click(objectsender, EventArgs e)
        {
            OpenFileDialogdlg = new OpenFileDialog();
            DialogResultdlgresult = dlg.ShowDialog();
            if(dlgresult != DialogResult.Cancel)
            {
                label1.Text = dlg.FileName;
                pictureBox1.ImageLocation = dlg.FileName;
            }
        }
        privatevoid CmdSave_Click(objectsender, EventArgs e)
        {
            byte[] @ImageData = ReadFile(label1.Text);
            SqlConnectioncnn = new SqlConnection(“Data Source=localhost;Initial Catalog=DatabaseName;Integrated Security=True”);
            stringSql = “INSERT INTO idcard(CustId,PHOTO)VALUES(“ + textBox1.Text  + “,@ImageData) “;
            SqlCommandSqlcmd = new SqlCommand(Sql, cnn);
            Sqlcmd.Parameters.Add(new SqlParameter(“@ImageData”,(object)ImageData));
            cnn.Open();
            Sqlcmd.ExecuteNonQuery();
            cnn.Close();
            MessageBox.Show(“Data Saved Successfully”);
        }
        //Read an image file into a byte array
        byte[] ReadFile(string Path)
        {
            byte[] data = null;
            FileInfoinfo = new FileInfo(Path);
            longNBytes = info.Length;
            FileStreamfstream = new FileStream(Path, FileMode.Open, FileAccess.Read);
            BinaryReaderBread = new BinaryReader(fstream);
            data = Bread.ReadBytes((int)NBytes);
            returndata;
        }
    }
}

Leave a Reply

Your email address will not be published. Required fields are marked *