Hi gokuldas,
I have created a sample please take its reference.
Namespaces
C#
using System.Data.SqlClient;
using System.IO;
using System.Windows.Forms;
VB.Net
Imports System.Data.SqlClient
Imports System.IO
Imports System.Windows.Forms
Code
C#
private void btnChooseFile_Click(object sender, EventArgs e)
{
string saveDirectory = Application.StartupPath.Replace("bin\\Debug", "Files");
using (OpenFileDialog openFileDialog1 = new OpenFileDialog())
{
if (openFileDialog1.ShowDialog() == DialogResult.OK)
{
if (!Directory.Exists(saveDirectory))
{
Directory.CreateDirectory(saveDirectory);
}
string fileName = Path.GetFileName(openFileDialog1.FileName);
string fileSavePath = Path.Combine(saveDirectory, fileName);
File.Copy(openFileDialog1.FileName, fileSavePath, true);
string constr = @"Data Source=.\SQL2014;Initial Catalog=AjaxSamples;Integrated Security=true";
using (SqlConnection conn = new SqlConnection(constr))
{
string sql = "INSERT INTO Files VALUES(@Name, @Path)";
using (SqlCommand cmd = new SqlCommand(sql, conn))
{
cmd.Parameters.AddWithValue("@Name", Path.GetFileName(fileName));
cmd.Parameters.AddWithValue("@Path", fileSavePath);
conn.Open();
cmd.ExecuteNonQuery();
conn.Close();
}
}
}
}
}
VB.Net
Private Sub btnChooseFile_Click(ByVal sender As Object, ByVal e As EventArgs) Handles btnChooseFile.Click
Dim saveDirectory As String = Application.StartupPath.Replace("bin\Debug", "Files")
Using openFileDialog1 As OpenFileDialog = New OpenFileDialog()
If openFileDialog1.ShowDialog() = DialogResult.OK Then
If Not Directory.Exists(saveDirectory) Then
Directory.CreateDirectory(saveDirectory)
End If
Dim fileName As String = Path.GetFileName(openFileDialog1.FileName)
Dim fileSavePath As String = Path.Combine(saveDirectory, fileName)
File.Copy(openFileDialog1.FileName, fileSavePath, True)
Dim constr As String = "Data Source=.\SQL2014;Initial Catalog=AjaxSamples;Integrated Security=true"
Using conn As SqlConnection = New SqlConnection(constr)
Dim sql As String = "INSERT INTO Files VALUES(@Name, @Path)"
Using cmd As SqlCommand = New SqlCommand(sql, conn)
cmd.Parameters.AddWithValue("@Name", Path.GetFileName(fileName))
cmd.Parameters.AddWithValue("@Path", fileSavePath)
conn.Open()
cmd.ExecuteNonQuery()
conn.Close()
End Using
End Using
End If
End Using
End Sub