You need to add the OpenFileDialog in the Form and a Button.
On Click of Button i have shown the FileDialog to choose the file to select the image or any other file.
Add the System.Configuration reference in you project and add the connectionString in the App.Config file.
Namespaces
using System.IO;
using System.Configuration;
using System.Data.SqlClient;
C#
private void button1_Click(object sender, EventArgs e)
{
this.openFileDialog1.ShowDialog();
}
private void openFileDialog1_FileOk(object sender, CancelEventArgs e)
{
string folderPath = "C:\\Images\\";
if (!Directory.Exists(folderPath))
{
Directory.CreateDirectory(folderPath);
}
string constr = ConfigurationManager.ConnectionStrings["constr"].ConnectionString;
string sqlStatment = "INSERT INTO [tblImages] VALUES(@FileName,@FilePath)";
using (SqlConnection con = new SqlConnection(constr))
{
using (SqlCommand cmd = new SqlCommand(sqlStatment, con))
{
con.Open();
cmd.Parameters.AddWithValue("@FileName", Path.GetFileName(this.openFileDialog1.FileName));
cmd.Parameters.AddWithValue("@FilePath", folderPath + Path.GetFileName(this.openFileDialog1.FileName));
cmd.ExecuteNonQuery();
con.Close();
}
}
//Save the file in folder
string fileLocation = OpenFileDialog1.FileName;
File.Copy(fileLocation, Path.Combine("C:\\Images\\", Path.GetFileName(fileLocation)), true);
}
VB Code
Private Sub Button1_Click(sender As System.Object, e As System.EventArgs) Handles Button1.Click
Me.OpenFileDialog1.ShowDialog()
End Sub
Private Sub OpenFileDialog1_FileOk(sender As System.Object, e As System.ComponentModel.CancelEventArgs) Handles OpenFileDialog1.FileOk
Dim folderPath As String = "C:\Images\"
If Not Directory.Exists(folderPath) Then
Directory.CreateDirectory(folderPath)
End If
Dim constr As String = ConfigurationManager.ConnectionStrings("constr").ConnectionString
Dim sqlStatment As String = "INSERT INTO [tblImages] VALUES(@FileName,@FilePath,null)"
Using con As New SqlConnection(constr)
Using cmd As New SqlCommand(sqlStatment, con)
con.Open()
cmd.Parameters.AddWithValue("@FileName", Path.GetFileName(Me.OpenFileDialog1.FileName))
cmd.Parameters.AddWithValue("@FilePath", folderPath & Path.GetFileName(Me.OpenFileDialog1.FileName))
cmd.ExecuteNonQuery()
con.Close()
End Using
End Using
'Save the file in folder
Dim fileLocation As String = OpenFileDialog1.FileName
File.Copy(fileLocation, Path.Combine("C:\Images\", Path.GetFileName(fileLocation)), True)
End Sub
SQL
CREATE TABLE [dbo].[tblImages](
[Id] [int] IDENTITY(1,1) NOT NULL,
[FileName] [varchar](50) NULL,
[FilePath] [varchar](200) NULL,
) ON [PRIMARY]
GO