Save image in to folder and its path to sql server database using csharp

08/03/2017   03:26:11 PM

Hello,in this c# tutorial i will explain how to save image in to the folder.then that image path in to the database.for select any file in c# windows application use openFile Dialog control

1 .Create a database name as Test.Create a table name as Imgtbl in this database.

 

2. Open vs.net Select C#--> Windows Application

 

3.Add the following controls to design the form

one textbox , one button & openFileDialog Control from toolbox for create select file dialog code.

Picture Box for display image

one Button for add save image path code

4.Add the following code for select image and copy image in to the folder and save that image path to the database

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();
}
}
}
}
 

Output

                   

Support us by Sharing