How to insert image in database and save specific folder in c#



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.IO;

namespace ADO.net_with_SQL
{
    public partial class Form1 : Form
    {
        SqlConnection con;
        SqlCommand cmd;
        public static string filepathname = "";
        public Form1()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            try
            {
                con = new SqlConnection(@"Data Source=SUSHIL-PC\SQLEXPRESS;Initial Catalog=sushil;Integrated Security=True;Pooling=False");
                con.Open();
                ConnectionState cst = con.State;
                if (cst == ConnectionState.Open)
                {
                    lblconnectiostatus.ForeColor = Color.Green;
                    lblconnectiostatus.Text = "Connection is open successfully";
                }
                
                   
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }



        }

        private void btnbrowse_Click(object sender, EventArgs e)
        {
            string filepath = null;
            //ofdpic.InitialDirectory = "c:\\";
            ofdpic.Filter = "jpg files (*.jpg)|*.jpg|All files (*.*)|*.*";
            ofdpic.FilterIndex = 1;
            ofdpic.RestoreDirectory = true;

            if (ofdpic.ShowDialog() == DialogResult.OK)
            {

                filepath = ofdpic.FileName;
                string filname = Path.GetFileName(filepath);
                filepathname = filname;
                pic.Image =  Image.FromFile(filepath);
                pic.Image.Save(Application.StartupPath + "\\Images\\"+filname);
            }
        }

        private void btnsave_Click(object sender, EventArgs e)
        {
            try
            {
                
                cmd = new SqlCommand("Insert into Emp_Details(Name,Address,Phone,path) values('" + txtname.Text + "','" + txtaddress.Text + "','" + txtphone.Text + "','"+filepathname+"')", con);

                int i = cmd.ExecuteNonQuery();

                if (i > 0)
                {
                    MessageBox.Show("record store successfully");
                }
            }
            catch (Exception ex)
            {
                cmd.Dispose();
                con.Close();
            }
        }
    }
}

Code Download Here

Comments