using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Data.SqlClient;
using System.Drawing;
using System.IO;
using System.Text;
using System.Windows.Forms;
namespace UploadImgFolderdb
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
SqlConnection con = new SqlConnection(@"Data Source=.\sqlexpress;Initial Catalog=Test;Integrated Security=True");
string displayimg, filePath;
string folderpath = @"D:\";
OpenFileDialog open = new OpenFileDialog();
SqlCommand cmdinsert;
//FOLLOWING CODE FOR SELECT IMAGE AND DISPLAY IN PICTURE BOX
private void btnSelect_Click(object sender, EventArgs e)
{
open.Filter = "Image Files(*.jpg; *.jpeg; *.gif; *.bmp)|*.jpg; *.jpeg; *.gif; *.bmp|all files|*.*";
if (open.ShowDialog() == DialogResult.OK)
{
// display image in picture box
displayimg = open.SafeFileName;
img.Image = new Bitmap(open.FileName);
// image file path
txtpath.Text = open.FileName;
filePath = open.FileName;
}
}
//FOLLOWING CODE FOR COPY SELECTED IMAGE TO THE FOLDER
AND SAVE PATH TO DATABASE
private void btnUpload_Click(object sender, EventArgs e)
{
if (filePath == "")
{
cmdinsert.Parameters.AddWithValue("@Name", "");
}
else
{
cmdinsert = new SqlCommand("Insert INTO Imgtbl Values(@Name)", con);
cmdinsert.CommandType = CommandType.Text;
cmdinsert.Parameters.AddWithValue("@Name", folderpath + Path.GetFileName(open.FileName));
File.Copy(filePath, Path.Combine(folderpath, Path.GetFileName(filePath)), true);
con.Open();
cmdinsert.ExecuteNonQuery();
MessageBox.Show("Image Saved");
con.Close();
}
}
}
}